如何使用jquery用json响应调用ajax请求? [英] How to call ajax request with json response using jquery?

查看:115
本文介绍了如何使用jquery用json响应调用ajax请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从下面的代码中用 jQuery.support.cors = true; 行打印成功.包括 jQuery.support.cors = true; 行将发出警告消息.那么如何在不失去功能的情况下避免这种情况呢?我的主要目标是调用一个休息的Web服务,该服务返回JSON数据,而我必须利用JSON数据.请帮助我如何做到这一点?请提供工作样本

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

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

推荐答案

  1. 您可能会错过添加 type //GET或POST(哪种类型的REST OPERATION)
  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 answer to understand the problem.

假设您在域abc.com上,并且要向域发出请求 xyz.com.为此,您需要跨越域边界,禁止进入 大部分浏览器.

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.

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

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.

这篇关于如何使用jquery用json响应调用ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆