Javascript 使用 jQuery 进行跨域 ajax JSONP 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11736431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:54:19  来源:igfitidea点击:

Make cross-domain ajax JSONP request with jQuery

javascriptjqueryajaxjson

提问by prabu R

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...

但我没有得到任何输出...任何人请帮忙...

回答by Abdul Munim

Concept explained

概念解释

Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.

您是否尝试进行跨域 AJAX 调用?意思是,您的服务未托管在同一 Web 应用程序路径中?您的 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 $.ajaxwith dataType: 'jsonp'meaning that jQuery is actually adding a new parameter to the query URL.

当您执行$.ajaxwithdataType: 'jsonp'意味着 jQuery 实际上是在向查询 URL 添加一个新参数时。

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.dothen 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 windowobject. This is nothing specific but does look something like this:

这种方法更像是一个实际附加在window对象中的代理。这没什么特别的,但看起来像这样:

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. i.e.

您的客户端代码似乎很好。但是,您必须修改您的服务器代码,以使用与查询字符串一起传递的函数名称来包装您的 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});

回答by Ninioe

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);
    }
});

回答by Yngve B-Nilsen

Your JSON-data contains the property Data, but you're accessing data. It's case sensitive

您的 JSON 数据包含属性Data,但您正在访问data. 区分大小写

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;
        },
    });
}        

EDITAlso City and Code is in the wrong case. (Thanks @Christopher Kenney)

编辑城市和代码也是错误的情况。(感谢@Christopher Kenney)

EDIT2It should also be json, and not jsonp (at least in this case)

EDIT2它也应该是 json,而不是 jsonp(至少在这种情况下)

UPDATEAccording to your latest comment, you should read this answer: https://stackoverflow.com/a/11736771/325836by Abdul Munim

更新根据你的最新评论,你应该阅读这个答案:https: //stackoverflow.com/a/11736771/325836 by Abdul Munim

回答by pirklajos

Try

尝试

alert(xml.Data[0].City)

Case sensitivly!

区分大小写!

回答by Erdem E.

you need to parse your xml with jquery json parse...i.e

你需要用 jquery json parse 来解析你的 xml...ie

  var parsed_json = $.parseJSON(xml);

回答by Stepan Suvorov

alert(xml.data[0].city);

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

use xml.data["Data"][0].city instead

使用 xml.data["Data"][0].city 代替

回答by rickdog

use open public proxy YQL, hosted by Yahoo. Handles XML and HTML

使用由 Yahoo 托管的开放公共代理 YQL。处理 XML 和 HTML

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

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