开发者

Jquery: probleme with $.ajax (json datatype)

I have a problem to refresh a bloc in my page.

Here is the request:

> $("#pwd_lost_link").click(function(){
    alert('1');
    $.ajax({
      type : 'POST',
      url: 'test.php',
      dataType: 'json',
      data :{"nom" : "akbar"},
      success : function(data){
        $("#main_bloc").append(data.msg);
        alert('2');
      },
      error : function(XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.responseText);
                                alert(errorThrown);             }
    });   })

and here is the php file

<?php  
 $return['nom'] = "ffrfrfrfr";
  echo json_encode($return)
?> 

It doesn't work. It give me a status error ( 0 ) and the page is automatically re开发者_如何学Pythonloaded

Thanks

Michaël


Confusing question Michael, not sure what you mean by "the page is automatically reloaded" but you should do 2 things:

In the $.ajax() method, make sure your success called back is handling the data correctly. You are looking for data.msg but I don't see where .msg comes from.

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        data: {},
        dataType: "json",
        url: url,
        success: function(data) {
            // parse data object so you can see what's being returned ex. alert(data) or alert(data[0]) or alert(data.nom)
        },
        error: function (xhr, status, error) {
            // XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp
            // check for errors  ex. alert(xhr.statusText);              
        } 
    });

On the PHP side, you may want to debug there to see what is being received and what you are sending back.

Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful.

And on a final note, if pwd_lost_link is a link elment a id="pwd_lost_link" href="..." then you will have to stop the browser from following the link before you process the AJAX.

$("#pwd_lost_link").click(function(e) {
    e.preventDefault(); 
    alert('1');
    $.ajax({      
   ...
});

If you aren't seeing the '1' being alerted then that is definitely your first problem.


You're trying to access data.msg, but your PHP script is only creating data.nom. So data.msg doesn't exist. Try changing data.msg to data.nom and see if this does what you want.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜