首页 > 解决方案 > 这里如何传递实际参数?

问题描述

JS函数不能用传递的参数调用

我已经通过 onclick 事件将实际参数从 php 文件传递​​到 div,它在页面上呈现,函数本身存在,但参数不传递给函数调用

形式参数与函数定义中一样,它不会被传递给 onclick 事件的内容所取代

http://localhost:8000/sknt1.php?reqStr

代码本身如下所示:

for ($i=0; $i<count($json_a["tarifs"]) ; $i++) {
 echo "<div onclick='fun(".$i.")' class='column' style='font-size:20px; width:100%'>

在页面上它看起来像这样(0 到 4):

<div onclick="fun(0)" class="column" style="font-size:20px; width:100%">
<div onclick="fun(1)" class="column" style="font-size:20px; width:100%">

等等。

fun() 是一个 AJAX 调用函数,它一次写入页面,我不能将它嵌入到 php for 循环中:

 <script type='text/javascript'>
function fun(reqStr) {
var xmlhttp = null;

function AjaxRequest(url){
  if(xmlhttp != null){
    if(xmlhttp.abort)
      xmlhttp.abort();
    xmlhttp = null;
  };
  if(window.XMLHttpRequest) // good browsers
    xmlhttp=new XMLHttpRequest();
  else if(window.ActiveXObject) // IE
    xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');

  if(xmlhttp == null)
    return null;

  xmlhttp.open('GET',url,false);
  xmlhttp.send(null);

  if(xmlhttp.status >= 200 && xmlhttp.status < 300)// 2xx is good enough
    return xmlhttp.responseText;
  else
    return null;
}
window.history.replaceState({}, '',`/sknt1.php?reqStr`);
var url = '/sknt1.php?reqStr';
  var contents = AjaxRequest(url);
  if(contents){
    document.documentElement.innerHTML = contents;}
}
</script>

我想要这个 Ajax 调用来替换传入的变量并替换 url 为 smth。比如http://localhost:8000/sknt1.php?0,有一个额外的 php 文件,它会在处理历史后呈现新页面,请帮助

标签: javascriptphpscope

解决方案


只需在 for 循环中创建一个变量 $iStr = ' " '.$i.' " ' 并传递新变量。


推荐阅读