简体   繁体   English

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

[英]AJAX POST request accepts number but not String

Alright, I have looked around for this problem, but I can only find references to JSON, which I am currently not using. 好了,我到处都在寻找这个问题,但是我只能找到对JSON的引用,而我目前没有使用。 The array value that has a number in it passes, and the DIV updates. 带有数字的数组值将通过,并且DIV将更新。 However, when ever I try to pass in a string, nothing happens. 但是,当我尝试传递字符串时,什么也没有发生。 Here is the code: 这是代码:

<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}

Please note I am doing testing with AJAX via IP.Board/IP.Content, so the tags and variables in {} are parsed by the IP.C engine. 请注意,我正在通过IP.Board / IP.Content使用AJAX进行测试,因此{。}中的标记和变量由IP.C引擎解析。

This code outputs two buttons labeled "yo" and "2". 此代码输出标记为“ yo”和“ 2”的两个按钮。 When "2" is clicked, the DIV updates correctly. 单击“ 2”时,DIV将正确更新。 When "yo" is clicked, nothing occurs. 单击“ yo”时,什么也没有发生。

The test.php file is very simple: test.php文件非常简单:

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

Thanks for any help beforehand. 感谢您的任何帮助。

This output HTML from your PHP Statement is invalid: 您的PHP语句的输出HTML无效:

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

Notice onclick=\\"nFunc(yo)\\"> 注意onclick=\\"nFunc(yo)\\">

See your string parameter is not enclosed in quotes and also those backslashes are not needed there. 请参阅您的字符串参数未包含在引号中,并且那里也不需要那些反斜杠。 That is why you see that error, which of course doesn't happen in case of a number. 这就是为什么您看到该错误的原因,如果出现数字,则该错误当然不会发生。

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

should be 应该

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

It works like a charm after that fix, I just tested. 我刚刚测试过,修复之后,它就像是一种魅力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM