jquery ajax call question

In a jQuery ajax statement I want to receive a payload from the server and process it in another function. I am just having trouble with the syntax of the function.

    $.ajax({
    url: 'mypgm.pgm',
    type:'POST', 
    dataType: 'json',
    data:   'action=add' +
             '&techno=' + techno +
             '&activity=' + activity, 
    success: ajax_callback(msg),
    error:function (xhr, ajaxOptions, thrownError){
                    alert(xhr.status);
                    alert(thrownError);
        }       
    });
}

    function ajax_callback(msg) { 

        alert(msg);
    }
    

Response

{"response": {
    "success": "0",
    "message": "The Activity has been added."
    }
}

A success callback handler for $.ajax() can take in the following values:

success(data, textStatus, jqXHR)

Source: http://api.jquery.com/jQuery.ajax/

So your function callback would be something like this:

function ajax_callback(data, textStatus, jqXHR)     
{
  alert(data.response)
}

Note how I created a named function this way, instead of assigning it to a var. If you only care about the data, you can just leave the last 2 parameters off:

function ajax_callback(data)     
{
  alert(data.response)
}

尝试这个:

$.ajax({
    url: 'mypgm.php',
    type: 'POST',
    dataType: 'json',
    data: 'action=add' + '&techno=' + techno + '&activity=' + activity,
    success: function(data) {
        alert(data)
    }
});

You callback should be defined before the ajax call and change the signature of the function to:

var ajax_callback = function(data, textStatus, xhr) {
    // parse the data.responseText to json
}

You could alternatively just use $.getJSON()

链接地址: http://www.djcxy.com/p/46186.html

上一篇: 在angular.js中解析JSONP $ http.jsonp()响应

下一篇: jquery ajax调用问题