jQuery 如何使用jquery使用json响应调用ajax请求?

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

How to call ajax request with json response using jquery?

jqueryajaxjson

提问by Kashif Khan

I cannot print success from the below code with the line jQuery.support.cors = true;. Including the line jQuery.support.cors = true;will give a warning message. So how can i avoid that without loosing the functionality? My main objective is to call a rest webservice which returns JSON data and i have to utilize the JSON data. Please help how can i achieve this? Please provide a working sample

我无法从下面的代码中使用jQuery.support.cors = true;行打印成功. 包括行jQuery.support.cors = true; 会给出警告信息。那么我怎样才能在不失去功能的情况下避免这种情况呢?我的主要目标是调用一个返回 JSON 数据的休息网络服务,我必须利用 JSON 数据。请帮助我如何实现这一目标?请提供工作样本

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.getJSON demo</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<script>
    jQuery.support.cors = true;
    $.ajax ({
        url: 'http://json-cricket.appspot.com/score.json',
        datatype: "json",
        success: function (e) {
            // Success callback
            alert("sucess");
        }})
</script>

</body>
</html>

回答by Praveen

  1. You might missed to add type//GET or POST, which type of REST OPEATION
  2. dataTypeis mispelled
  3. Missed to add contentType
  1. 您可能错过添加type//GET 或 POST,哪种类型的 REST OPEATION
  2. dataType拼错了
  3. 错过添加 contentType


 $.ajax({
            type: "POST", //rest Type
            dataType: 'jsonp', //mispelled
            url: "http://json-cricket.appspot.com/score.json",
            async: false,
            contentType: "application/json; charset=utf-8",
            success: function (msg) {
                console.log(msg);                
            }
 });

Updates:While trying to figure out the reason, I think this is the best answerto understand the problem.

更新:在试图找出原因的同时,我认为这是理解问题的最佳答案

Say you're on domain abc.com, and you want to make a request to domain xyz.com. To do so, you need to cross domain boundaries, a no-no in most of browserland.

The one item that bypasses this limitation is tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really DO anything with the results, the script just gets evaluated.

Enter JSONP.When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle.

假设您在域 abc.com 上,并且想要向域 xyz.com 发出请求。为此,您需要跨越域边界,这在大多数浏览器领域都是禁忌。

绕过此限制的一项是标签。当您使用脚本标签时,域限制被忽略,但在正常情况下,您不能真正对结果做任何事情,脚本只是被评估。

输入JSONP当您向启用 JSONP 的服务器发出请求时,您会传递一个特殊参数,该参数会告诉服务器有关您的页面的一些信息。这样,服务器就能够以您的页面可以处理的方式很好地包装其响应。

回答by Maxim Manco

The best shot will be using a jsonp request. For this just specify dataTypeto be jsonp

最好的办法是使用 jsonp 请求。为此,只需指定dataTypejsonp

$.ajax({
    url: 'http://json-cricket.appspot.com/score.json',
    dataType: 'jsonp',
    success: function (data) {
        console.log(data);        
    }
});

See example on jsFidle

请参阅jsFidle上的示例

回答by Suganth G

Try this , it gives best results. This was used in REST Architecture, the response speed is very high

试试这个,它给出了最好的结果。这个用在REST架构中,响应速度非常高

function CallService(sucessData) {
    $.ajax({
        // Add code for Cross Domain
        headers: getHeaders(),
        type: varType, //GET or POST or PUT or DELETE verb
        url: varUrl, // Location of the service
        data: varData, //Data sent to server
        contentType: varContentType, // content type sent to server
        dataType: varDataType, //Expected data format from server
        processdata: varProcessData, //True or False
        crossDomain: true,
        timeout: 200000,
        success: sucessData,
        error: function (xhr) {// When Service call fails
            alert("Error: " + xhr.responseText);
        }
    });
}

回答by Gurminder Singh

If you are requesting Cross-Domainservice, then you need to include jQuery.support.cors = true;. And the correct AJAX code would be:

如果您请求跨域服务,那么您需要包含jQuery.support.cors = true; . 正确的 AJAX 代码是:

 $.ajax ({
    url: 'http://json-cricket.appspot.com/score.json',
    dataType: "json",
    contentType: "application/json",
    success: function (jsonData) {
        // Success callback
        alert("sucess");
    },
    error: function() {
        //any error to be handled
    }
 });

回答by Gurpreet Singh

CORS (Cross-Origin Resource Sharing) isn't the same as XSS.

CORS(跨域资源共享)与 XSS 不同。

$.support.corscontains the result of a test that tests whether or not the current browser supports cors. changing it doesn't make the browser support cors.

$.support.cors包含测试当前浏览器是否支持 cors 的测试结果。更改它不会使浏览器支持 cors。

Also, your server has to support CORSby returning the proper headers.

此外,您的服务器必须CORS通过返回正确的标头来支持。