开发者

cannot get a response from jquery / ajax

This is giving me headaches, AGAIN. I either don't understand this ajax response stuff at all, or it's poorly coded.

Let's establish an extremely simple example to work with:

register.php:

<?php
echo 'I want some response !!';
?>

ajax call:

$.ajax({
 url: '/register.php',
 type: 'POST',
 data: $('#form-registracia').serializeArray(),
 success: function(e){
   var response = e.responseText;
   alert(response);
 }
});

Alert says undefined. Why? I tried messing with it for hours now, I read the jquery site, nothing helps. I'm sure the PHP file gets executed and that the echo is sent 开发者_如何学Goback to ajax.

Thanks in advance!


you are getting undefined because the response returned from the server is contained within e, not e.responseText. responseText is a property of the XHR object, but jQuery encapsulates that for you and provides the responseText as the argument in the success method.

so in short, change it to this:

success: function(e){ var response = e; alert(response); }


The argument to "success" is the response text itself; you're asking a String for its responseText member, which is indeed undefined. Just use the argument directly.

There's a three-argument form of the success function in which the last argument is the XHR object you're looking for.


try alert(e). You aren't sending an object so e doesn't have a property responseText (it's just plain text). In case you want to see the request as it hits your browser use fiddler or firebug to look at the request and response headers.


You need to read the jQuery api a little better:

success(data, textStatus, jqXHR)Function, Array

A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

The first parameter in the success callback is your data. You should be typing alert(e).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜