sunmingtao / sample-code

3 stars 4 forks source link

jQuery jsonp request explanation #228

Closed sunmingtao closed 3 years ago

sunmingtao commented 3 years ago

jQuery:

$.ajax({
    url: 'http://localhost:8080/student/1'
    dataType: "jsonp",
    success: function(data){
      alert(data);
    },
})

When jQuery sees the dataType is 'jsonp', it will automatically append a callback request para with a random value .

So the request looks like http://localhost:8080/student/1?callback=jQuery1234567_987654

The server needs to wrap the json response with this callback value.

e.g.

If the json response is {'name': 'john', 'age': 1}, then the actual response needs to be "jQuery1234567_987654({'name': 'john', 'age': 1})"

Note the data in the success callback already has the jQuery1234567_987654 bit stripped off. In this example, data = {'name': 'john', 'age': 1}

If the server doesn't provide response in this format, jQuery's success method won't be able to handle the response. And there is no error message.

You can manually add the callback param. The benefit is that you can place it anywhere you want at the URL. If it involves complex redirect, it can be useful. url: 'http://localhost:8080/student/1?callback=?'

or

url: 'http://localhost:8080/student/1?redirect_url=http://localhost:8081&callback=?'