jQuery 跨域 Ajax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16989505/
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-26 18:13:13  来源:igfitidea点击:

jQuery Cross Domain Ajax

jqueryajaxjsonjquery-mobilecordova

提问by Miqdad Ali

My ajax code is

我的ajax代码是

$.ajax({
    type: 'GET',
    dataType: "jsonp",
    processData: false,
    crossDomain: true,
    jsonp: false,
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        console.log("in");
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

This is a cross domain ajax request.

这是一个跨域ajax请求。

I am getting correct response for the request, while checking with firebug i can see that response.

我得到了对请求的正确响应,在使用 firebug 进行检查时,我可以看到该响应。

This is the response I am getting in firebug response and while accessing this url through web browser

这是我在萤火虫响应和通过网络浏览器访问此 url 时得到的响应

{"AuthenticateUserResult":"{\"PKPersonId\":1234,\"Salutation\":null,\"FirstName\":\"Miqdad\",\"LastName\":\"Kumar\",\"Designation\":null,\"Profile\":\"\",\"PhotoPath\":\"\/UploadFiles\/\"}"}

But I am getting error

但我收到错误

SyntaxError: invalid label

{"AuthenticateUserResult":"{\"PKPersonId\":8970,\"Salutation\

Whether I need to use any other method to get it works. I want to implement this in phonegap+jquery mobile app.

我是否需要使用任何其他方法才能使其正常工作。我想在 phonegap+jquery 移动应用程序中实现这个。

Also, I don't have any access to the web service

另外,我没有任何访问网络服务的权限

If I disable chrome web security it's working fine

如果我禁用 chrome 网络安全它工作正常

回答by EWit

Looks like the inner JSON struct is passed along as a string. You'll have to JSON.parse() it once more to get that data as an object.

看起来内部 JSON 结构是作为字符串传递的。您必须再次使用 JSON.parse() 才能将该数据作为对象获取。

try {
  responseData = JSON.parse(responseData);
}
catch (e) {}

Edit: Try the following:

编辑:尝试以下操作:

$.ajax({
    type: 'GET',
    dataType: "json",
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        console.log("in");
        var data = JSON.parse(responseData['AuthenticateUserResult']);
        console.log(data);
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

回答by ElmoVanKielmo

Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...)tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult":and interesting data is after this, try:

不幸的是,这个 Web 服务似乎返回包含另一个 JSON 的 JSON - 解析内部 JSON 的内容是成功的。解决方案很难看,但对我有用。JSON.parse(...)尝试转换整个字符串并失败。假设你总是得到答案开始,{"AuthenticateUserResult":有趣的数据是在这之后,尝试:

$.ajax({
    type: 'GET',
    dataType: "text",
    crossDomain: true,
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        var authResult = JSON.parse(
            responseData.replace(
                '{"AuthenticateUserResult":"', ''
            ).replace('}"}', '}')
        );
        console.log("in");
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

It is very important that dataTypemust be textto prevent auto-parsing of malformed JSON you are receiving from web service.

dataType必须text防止自动解析您从 Web 服务接收到的格式错误的 JSON ,这一点非常重要。

Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResultalong with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

基本上,我通过删除最上面的大括号和键AuthenticateUserResult以及前导和尾随引号来消除外部 JSON 。结果是一个格式良好的 JSON,准备好进行解析。

回答by Subir Kumar Sao

The response from server is JSON String format. If the set dataType as 'json' jquery will attempt to use it directly. You need to set dataType as 'text' and then parse it manually.

来自服务器的响应是 JSON 字符串格式。如果将 dataType 设置为 'json' jquery 将尝试直接使用它。您需要将 dataType 设置为 'text',然后手动解析它。

$.ajax({
    type: 'GET',
    dataType: "text", // You need to use dataType text else it will try to parse it.
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        console.log("in");
        var data = JSON.parse(responseData['AuthenticateUserResult']);
        console.log(data);
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

回答by Techie

If you are planning to use JSONPyou can use getJSONwhich made for that. jQuery has helper methods for JSONP.

如果您打算使用,JSONP您可以使用getJSONwhich made 。jQuery 为JSONP.

$.getJSON( 'http://someotherdomain.com/service.svc&callback=?', function( result ) {
       console.log(result);
});

Read the below links

阅读以下链接

http://api.jquery.com/jQuery.getJSON/

http://api.jquery.com/jQuery.getJSON/

Basic example of using .ajax() with JSONP?

将 .ajax() 与 JSONP 一起使用的基本示例?

Basic how-to for cross domain jsonp

跨域 jsonp 的基本操作方法

回答by PJR

When using "jsonp", you would basically be returning data wrapped in a function call, something like

使用“jsonp”时,您基本上会返回包含在函数调用中的数据,例如

jsonpCallback([{"id":1,"value":"testing"},{"id":2,"value":"test again"}])
where the function/callback name is 'jsonpCallback'.

If you have access to the server, please first verify that the response is in the correct "jsonp"format

如果您可以访问服务器,请首先验证响应的"jsonp"格式是否正确

For such a response coming from the server, you would need to specify something in the ajax call as well, something like

对于来自服务器的此类响应,您还需要在 ajax 调用中指定一些内容,例如

jsonpCallback: "jsonpCallback",  in your ajax call

Please note that the name of the callback does not need to be "jsonpCallback" its just a name picked as an example but it needs to match the name(wrapping) done on the server side.

请注意,回调的名称不需要是“ jsonpCallback”,它只是作为示例选择的名称,但它需要匹配在服务器端完成的名称(包装)。

My first guess to your problem is that the response from the server is not what it should be.

我对您的问题的第一个猜测是来自服务器的响应不是它应该的。

回答by JoDev

You just have to parse the string using JSON.parselike this :

你只需要像这样使用JSON.parse解析字符串:

var json_result = {"AuthenticateUserResult":"{\"PKPersonId\":1234,\"Salutation\":null,\"FirstName\":\"Miqdad\",\"LastName\":\"Kumar\",\"Designation\":null,\"Profile\":\"\",\"PhotoPath\":\"\/UploadFiles\/\"}"};

var parsed = JSON.parse(json_result.AuthenticateUserResult);
console.log(parsed);

Here you will have something like this :

在这里你会有这样的事情:

Designation
null

FirstName
"Miqdad"

LastName
"Kumar"

PKPersonId
1234

PhotoPath
"/UploadFiles/"

Profile
""

Salutation
null

And for the request, don't forget to set dataType:'jsonp'and to add a file in the root directory of your site called crossdomain.xmland containing :

对于请求,不要忘记dataType:'jsonp'在站点的根目录中设置并添加一个名为crossdomain.xml并包含以下内容的文件:

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<!-- Read this: www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->

<!-- Most restrictive policy: -->
<site-control permitted-cross-domain-policies="none"/>

<!-- Least restrictive policy: -->
<!--
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" to-ports="*" secure="false"/>
<allow-http-request-headers-from domain="*" headers="*" secure="false"/>
-->
</cross-domain-policy>

EDIT to take care of Sanjay KumarPOST

编辑以照顾Sanjay KumarPOST

So you can set the callback function to be called in the JSONP using jsonpCallback!

所以你可以设置回调函数在 JSONP 中使用jsonpCallback!

$.Ajax({
    jsonpCallback : 'your_function_name',
    //OR with anonymous function
    jsonpCallback : function(data) {
        //do stuff
    },
    ...
});

回答by Sanjay Kumar

Here is the snippets from my code.. If it solves your problems..

这是我的代码片段.. 如果它解决了您的问题..

Client Code :

客户代码:

Set jsonpCallBack : 'photos' and dataType:'jsonp'

设置 jsonpCallBack : 'photos' 和 dataType:'jsonp'

 $('document').ready(function() {
            var pm_url = 'http://localhost:8080/diztal/rest/login/test_cor?sessionKey=4324234';
            $.ajax({
                crossDomain: true,
                url: pm_url,
                type: 'GET',
                dataType: 'jsonp',
                jsonpCallback: 'photos'
            });
        });
        function photos (data) {
            alert(data);
            $("#twitter_followers").html(data.responseCode);
        };

Server Side Code (Using Rest Easy)

服务器端代码(使用 Rest Easy)

@Path("/test_cor")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String testCOR(@QueryParam("sessionKey") String sessionKey, @Context HttpServletRequest httpRequest) {
    ResponseJSON<LoginResponse> resp = new ResponseJSON<LoginResponse>();
    resp.setResponseCode(sessionKey);
    resp.setResponseText("Wrong Passcode");
    resp.setResponseTypeClass("Login");
    Gson gson = new Gson();
    return "photos("+gson.toJson(resp)+")"; // CHECK_THIS_LINE
}