AJAX POST请求接受数字,但不接受字符串


AJAX POST request accepts number but not String

好吧,我已经寻找了这个问题,但我只能找到JSON的引用,我目前没有使用。包含数字的数组值传递过去,DIV更新。然而,当我试图传递一个字符串时,什么也没有发生。下面是代码:

<php> 
$cont = array();
$cont[] = 'yo';
$cont[] = '2';
foreach($cont as $c){
  $statement .= '<button type='"button'" onclick='"nFunc('.$c.')'">'.$c.'</button>';
}
</php>
<script>
function nFunc(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("POST","test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("p="+str);
}
</script>
<div id="myDiv">Default</div>
{$statement}

请注意,我正在通过IP. board/IP做AJAX测试。内容,因此{}中的标记和变量由IP.C引擎解析。

此代码输出两个标记为"yo"answers"2"的按钮。当单击"2"时,DIV会正确更新。当"yo"被点击时,什么也没有发生。

test.php文件非常简单:
<?php
$hello = $_POST['p'];
echo $hello;
?>

感谢您事先的帮助

PHP语句的输出HTML无效:

<button type='"button'" onclick='"nFunc(yo)'">yo</button><button type='"button'" onclick='"nFunc(2)'">2</button>

通知onclick='"nFunc(yo)'">

请注意您的字符串参数没有括在引号中,也不需要在那里使用反斜杠。这就是为什么你会看到错误,这当然不会发生在数字的情况下。

$statement .= '<button type='"button'" onclick='"nFunc('.$c.')'">'.$c.'</button>';
应该

$statement .= '<button type="button" onclick="nFunc('''.$c.''')">'.$c.'</button>';

我刚测试过,修复后效果很好