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

时间:2013-03-18 07:02:04

标签: php javascript html ajax

好吧,我已经四处寻找这个问题,但我只能找到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.Content进行AJAX测试,因此{}中的标签和变量由IP.C引擎解析。

此代码输出两个标有“yo”和“2”的按钮。单击“2”时,DIV会正确更新。单击“yo”时,不会发生任何事情。

test.php文件非常简单:

<?php
$hello = $_POST['p'];
echo $hello;
?>

事先感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

HTML声明中的此输出PHP无效:

<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>';

在修复之后,它就像一个魅力,我刚刚测试过。