Home > Web Front-end > JS Tutorial > How Can I Make Cross-Domain AJAX JSONP Requests with jQuery?

How Can I Make Cross-Domain AJAX JSONP Requests with jQuery?

Barbara Streisand
Release: 2024-11-25 15:21:13
Original
424 people have browsed it

How Can I Make Cross-Domain AJAX JSONP Requests with jQuery?

Making Cross-Domain AJAX JSONP Requests with jQuery

In your code snippet, you're attempting to parse JSON data from a service hosted on a different domain using jQuery's AJAX feature. However, cross-domain AJAX requests require additional considerations to work successfully.

Cross-Domain AJAX

By default, browsers restrict AJAX requests to same-origin URLs due to security concerns. To overcome this, you must implement JSONP (JSON with Padding), which allows you to make cross-domain requests using a <script> tag.</p> <p><h3>Method Injection</h3></p> <p>In your server-side code, you need to support method injection. When you use jQuery with 'dataType: 'jsonp'', it appends a query parameter to the URL with a randomly generated method name. Your server must then wrap the JSON response with this method name as a function call.</p> <p><h3>Corrected Code</h3></p> <p>Ensure that your server is correctly wrapping the JSON response with the method name passed in the query string. For example, if your query string includes ?callback=my_callback_method, your server should respond with:</p> <p>my_callback_method({your json serialized data});</p> <p>Once this is implemented, your jQuery code should parse the JSON data successfully:</p> <p><br><script type="text/javascript"><br>var result;<br>function jsonparser1() {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">$.ajax({ type: &quot;GET&quot;, url: &quot;http://10.211.2.219:8080/SampleWebService/sample.do&quot;, dataType: &quot;jsonp&quot;, success: function (xml) { alert(xml.data[0].city); result = xml.code; document.myform.result1.value = result; }, });</pre><div class="contentsignin">Copy after login</div></div> <p>} <br></script>

The above is the detailed content of How Can I Make Cross-Domain AJAX JSONP Requests with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template