ajax jquery always running Error
Everytime I run my ajax jquery function I get an error, this goes for all my ajax calls. here is an example of my code
function FindContact(CompanyName,DivisionName,FirstName,LastName) {
$.ajax({
url: 'Path',
dataType: "json",
async:false,
type:'post',
data: {'FirstName':FirstName,'LastName':LastName,'DivisionName':DivisionName,'CompanyName':CompanyName},
success: DisplayContacts,
error: ErrorMsg
});
}
to get around this I use this
function ErrorMsg(result) {
if (result.status == 200 && result.statusText == 'OK') {
DisplayContacts(result);
}
else {
al开发者_如何学Pythonert("FAILED : " + result.status + ' ' + result.statusText);
}
}
this is tough because I need to create method like this for every ajax request.
why does it run the error code 1st???
Please help!
Ensure that what you are returning is valid json. If its not, and everything goes correct on the server, $.ajax will go to error rather than success.
function FindContact(CompanyName,DivisionName,FirstName,LastName) {
$.ajax({
url: 'Path',
dataType: "html or json",
async:false,
type:'post',
data: {'FirstName':FirstName,'LastName':LastName,'DivisionName':DivisionName,'CompanyName':CompanyName},
success: DisplayContacts,
error: ErrorMsg
});
}
A quick to check if the json is valid is to just switch dataType to html and see the success is being fired. If it is than your json is invalid, if your still getting the same problem thers something else wrong.
Another way to check if valid json is being returned is, open up firebug and when the request gets sent, click on the response tab, copy the response and got to jsonlint.com to check if its valid.
Jquery ajax docs
My solution was a difference in Accept-Type and Content-Type headers. If the client-side request's Accept-Type header does not match the server-side response's Content-Type header, Jquery will call the error callback.
Jquery, by default, sets the Accept-Type header to application/json
. However, my server was sending a response with Content-Type application/x-javascript
. My fix was to change the server-side response Content-Type header to the appropriate application/json
.
I was facing the same issue when making an ajax call using jquery ajax. I fixed it using the following code:
$.ajax({
url: "/url",
dataType: 'text',
success: function(result){ alert(result); },
error: ErrorMsg,
});
Note: dataType: 'text' parameter, it worked for me.
精彩评论