I try to use XMLHttpRequest() to post data to a url. I wrote the following 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);}
then i need to pass two php variables i开发者_开发知识库nto this function in php file, one is a url, another is json data to be posted.
$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\")' />";
After execution, i got the following error from firebug:
missing ) after argument list
Here is what I suggest. To clean up the code, let's removed the embedded onclick and give it an ID:
$editpage->editFormTextTop = "<input type='button' id="requestBtn" />";
Now in the head of your script you can initialize the values;
Note: This code is simplified
<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>
I'm assuming that your second block of code has a transcription error, and that the "$encoded_params" PHP variable is supposed to be "$json_str". When that variable is expanded into the HTML for that <input>
element, the double quote characters in it will result in an error, because the input element will look like this:
<input type='button'value='hello' onclick='makePostRequest("http://www.hello.com", "{"format": "json", "event": "revert", "api_key": "something"}")' />
See how that call to "makePostRequest()" is messed up? The "encoded_params" string, with its own embedded double-quote characters, ends up being a malformed string constant.
Your title and content text don't match. If you want to pass php variable to javascript simply do
var yourvar = '<?php echo $your_php_var; ?>';
精彩评论