Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

javascript - Callback function for JSONP with jQuery AJAX

I didn't quite understand how to work with the callback for the ajax function of jQuery.

I have the following code in the JavaScript:

try {
    $.ajax({
        url: 'http://url.of.my.server/submit?callback=?',
        cache: false,
        type: 'POST',
        data: $("#survey").serialize(),
        dataType: "jsonp",
        timeout: 200,
        crossDomain: true,
        jsonp: 'jsonp_callback',
        success: function (data, status) {
            mySurvey.closePopup();
        },
        error: function (xOptions, textStatus) {
            mySurvey.closePopup();
        }
    });
} catch (err) {
    mySurvey.closePopup();
}

And on the server side (AppEngine / Python) I get the value of the callback parameter and respond with

self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
self.response.out.write(callback + '({"msg": "ok"});')

But then I get an "Error: jQuery152042227689944248825_1317400799214 is not a function" in the browser console.

What is the proper way to handle this? Right now I get the results that I need, but the fact that I know it's not right is bothering me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is what I do on mine

$(document).ready(function() {
  if ($('#userForm').valid()) {
    var formData = $("#userForm").serializeArray();
    $.ajax({
      url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',
      type: "GET",
      data: formData,
      dataType: "jsonp",
      jsonpCallback: "localJsonpCallback"
    });
  });

function localJsonpCallback(json) {
  if (!json.Error) {
    $('#resultForm').submit();
  } else {
    $('#loading').hide();
    $('#userForm').show();
    alert(json.Message);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...