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.
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: "GET",
url: "http://10.211.2.219:8080/SampleWebService/sample.do",
dataType: "jsonp",
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!