简体   繁体   English

使用jQuery创建跨域ajax JSONP请求

[英]Make cross-domain ajax JSONP request with jQuery

I would like to parse JSON array data with jquery ajax with the following code: 我想用jquery ajax用以下代码解析JSON数组数据:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
    var result;
    function jsonparser1() {
        $.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;
            },
        });
    }        
</script>    
</head>
<body>
<p id="details"></p>
<form name="myform">
    <input type="button" name="clickme" value="Click here to show the first name" onclick=jsonparser1() />
    <input type="text" name="result1" readonly="true"/>        
</form>
</body>
</html>

My JSON data is: 我的JSON数据是:

{"Data":   [{"Address":"chetpet","FirstName":"arulmani","Id":1,"LastName":"sathish","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"ramaraj","Id":3,"LastName":"rajesh","City":"chennai"},{"Address":"ramapuram","FirstName":"yendran","Id":3,"LastName":"sathi","City":"chennai"}],"Code":true}

But i am not getting any output...anybody please help out... 但我没有得到任何输出......任何人请帮助...

Concept explained 概念解释

Are you trying do a cross-domain AJAX call? 您是否尝试进行跨域AJAX调用? Meaning, your service is not hosted in your same web application path? 这意味着,您的服务不在您的同一Web应用程序路径中托管? Your web-service must support method injection in order to do JSONP. 您的Web服务必须支持方法注入才能执行JSONP。

Your code seems fine and it should work if your web services and your web application hosted in the same domain. 您的代码似乎很好,如果您的Web服务和Web应用程序托管在同一个域中,它应该可以正常工作。

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL. 当您使用dataType: 'jsonp'执行$.ajax ,意味着jQuery实际上是在查询URL中添加新参数。

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method} . 例如,如果您的URL是http://10.211.2.219:8080/SampleWebService/sample.do那么jQuery将添加?callback={some_random_dynamically_generated_method}

This method is more kind of a proxy actually attached in window object. 这种方法实际上是附加在window对象中的一种代理。 This is nothing specific but does look something like this: 这没什么特别的,但看起来像这样:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Summary 摘要

Your client code seems just fine. 您的客户端代码似乎没问题。 However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. 但是,您必须修改服务器代码以使用通过查询字符串传递的函数名来包装JSON数据。 ie

If you have reqested with query string 如果您已经重新使用查询字符串

?callback=my_callback_method

then, your server must response data wrapped like this: 那么,你的服务器必须响应这样包装的数据:

my_callback_method({your json serialized data});

You need to use the ajax-cross-origin plugin: http://www.ajax-cross-origin.com/ 您需要使用ajax-cross-origin插件: http//www.ajax-cross-origin.com/

Just add the option crossOrigin: true 只需添加选项crossOrigin:true

$.ajax({
    crossOrigin: true,
    url: url,
    success: function(data) {
        console.log(data);
    }
});

Your JSON-data contains the property Data , but you're accessing data . 您的JSON数据包含属性Data ,但您正在访问data It's case sensitive 这是区分大小写的

function jsonparser1() {
    $.ajax({
        type: "GET",
        url: "http://10.211.2.219:8080/SampleWebService/sample.do",
        dataType: "json",
        success: function (xml) {
            alert(xml.Data[0].City);
            result = xml.Code;
            document.myform.result1.value = result;
        },
    });
}        

EDIT Also City and Code is in the wrong case. 编辑此外城市和代码是错误的情况。 (Thanks @Christopher Kenney) (谢谢@Christopher Kenney)

EDIT2 It should also be json, and not jsonp (at least in this case) EDIT2它也应该是json,而不是jsonp(至少在这种情况下)

UPDATE According to your latest comment, you should read this answer: https://stackoverflow.com/a/11736771/325836 by Abdul Munim 更新根据您的最新评论,您应该阅读以下答案: https ://stackoverflow.com/a/11736771/325836 by Abdul Munim

Try 尝试

alert(xml.Data[0].City)

Case sensitivly! 案例敏感!

你需要用jquery json解析解析你的xml ...即

  var parsed_json = $.parseJSON(xml);

alert(xml.data[0].city); 警报(xml.data [0]。市);

use xml.data["Data"][0].city instead 使用xml.data [“Data”] [0] .city代替

use open public proxy YQL, hosted by Yahoo. 使用由Yahoo托管的开放公共代理YQL。 Handles XML and HTML 处理XML和HTML

https://gist.github.com/rickdog/d66a03d1e1e5959aa9b68869807791d5 https://gist.github.com/rickdog/d66a03d1e1e5959aa9b68869807791d5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM