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
145 views
in Technique[技术] by (71.8m points)

javascript - Cross-site AJAX using jQuery

I have an existing jQuery plugin which makes a lot of AJAX calls (mostly JSON). I am wondering what is the quickest to allow it to do cross-site calls i.e. the $.get and $.post URL's will not be from the same domain.

I have heard of JSONP, but was wondering if someone could give me an concrete example to go about the whole process. I want to make minimal changes if possible to my script. Should I use a proxy.php of sorts?

Thank you for your time.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

JSONP will allow you to do cross-site calls. See jQuery docs on that matter.

The concept is simple: instead of doing a normal Ajax call, jQuery will append a <script> tag to your <head>. In order for this to work, your JSON data needs to be wrapped in a function call.

Your server needs to send information in such way (PHP example):

$json = json_encode($data);
echo $_GET['jsonp_callback'] . '(' . $json . ');';

Then, you can use jQuery to fetch that information:

$.ajax({
  dataType: 'jsonp',
  jsonp: 'jsonp_callback',
  url: 'http://myotherserver.com/getdata',
  success: function () {
    // do stuff
  },
});

More information is available here: What is JSONP?


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

1.4m articles

1.4m replys

5 comments

57.0k users

...