when i make a AJAX request with this code, it returns the status as 0. what did i do wrong? Also, this code is only designed to work in Firefox for various reasons.
var ajax;
function connectToOtherServer(server,port,userid,password){
ajax=new XMLHttpRequest();
ajax.onreadystatechange=validateConnection;
params='userid='+encodeURIComponent(userid)+'&password='+encodeURIComponent(password);
alert('http://'+server+':'+port+'/ok.txt');
ajax.open('POST','http://'+server+':'+port+'/ok.txt',true);
ajax.setRequestHeader("Content-type","application/x-www-form-开发者_如何学Pythonurlencoded");
ajax.setRequestHeader("Content-length",params.length);
ajax.setRequestHeader("Connection","close");
ajax.send(params);
}
function validateConnection(){
if(ajax.readyState===4){
if(ajax.status===200){
alert(ajax.responseText);
}else{
alert(ajax.status);
}
}
}
If you try to connect to another server, the same origin policy will stop you:
The term "origin" is defined using the domain name, application layer protocol, and (in most browsers) TCP port of the HTML document running the script. Two resources are considered to be of the same origin if and only if all these values are exactly the same.
jquery.com You can only connect to another server if you use JSONP and a callback. The other server will need to support the JSONP/callback mechanism. This method involves creating a new script tag then having the remote server return the callback code into this script tag. Look at the jQuery source code (or simply use it) to see it handles JSONP.
The basic idea is to create a script tag with the source as the remote URL. The remote method returns a "script" containing a function call using the callback and the resultant JSON data.
I've recently run into this issue. I've been using AJAX to submit form results so that page elements can update automatically. My domain calls were correct. SELECT
statements on the database would work, but INSERT
, UPDATE
, and DELETE
statements would not.
Alerts showing progress through the javascript indicated that the call was running correctly, but it would never make it to the php portion of the process. The simple answer was that the form's onsubmit
element needed to include return false;
. After adding that, the things ran smoothly.
<form name="form" action="" method="post" onsubmit="ProcessRequest(this);return false;">
Hope this helps.
精彩评论