在参数列表之后传递php变量到javascript函数错误:缺失)

时间:2011-08-04 17:29:16

标签: php javascript json

我尝试使用XMLHttpRequest()将数据发布到网址。 我写了以下javascript:

function makePostRequest(url, params) {
var httpRequest = new XMLHttpRequest();
httpRequest.open("POST", url, true);
//Send the proper header information along with the request
httpRequest.setRequestHeader("Content-type", "application/json");

httpRequest.onreadystatechange = function() {//Call a function when the state changes.
    if(httpRequest.readyState == 4 && httpRequest.status == 200) {
        alert(httpRequest.responseText);
    }
}
httpRequest.send(params);}

然后我需要在php文件中将两个php变量传递给这个函数,一个是url,另一个是要发布的json数据。

$url = "http://www.hello.com";
$json_str = "{\"format\": \"json\",
          \"event\": \"revert\",
      \"api_key\": \"$wgAPIKey\"}";

$editpage->editFormTextTop = 
          "<input type='button'value='hello' onclick='makePostRequest(\"$url\", \"$json_str\")' />";

执行后,我从firebug得到以下错误:

missing ) after argument list

3 个答案:

答案 0 :(得分:0)

我假设您的第二个代码块有转录错误,并且“$ encoded_pa​​rams”PHP变量应该是“$ json_str”。当该变量扩展为该<input>元素的HTML时,其中的双引号字符将导致错误,因为input元素将如下所示:

<input type='button'value='hello' onclick='makePostRequest("http://www.hello.com", "{"format": "json", "event": "revert", "api_key": "something"}")' />

看看对“makePostRequest()”的调用是如何搞砸的?带有自己嵌入的双引号字符的“encoded_pa​​rams”字符串最终成为格式错误的字符串常量。

答案 1 :(得分:0)

您的标题和内容文字不符。如果你想将php变量传递给javascript,只需执行

var yourvar = '<?php echo $your_php_var; ?>';

答案 2 :(得分:0)

这是我的建议。要清理代码,我们删除嵌入的onclick并为其提供ID:

$editpage->editFormTextTop = "<input type='button' id="requestBtn" />";

现在在脚本的头部,您可以初始化值;

注意:此代码已简化

<script>
window.onload = function() {
   var url = "http://www.hello.com";
   var jsonString = "{\"format\": \"json\",\"event\": \"revert\",\"api_key\": \"<?php echo $wgAPIKey ?>\"}";
   // now we can assign the function to the button
   document.getElementById("requestBtn").onclick = function () {
      makePostRequest(url,json_string);
   }
}
</script>