jQuery $.getJSON 不起作用

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

$.getJSON not working

jquerygetjson

提问by Jimmy Lin

I search related topic in jQuery. But I didn't saw any method to solve my problem.

我在 jQuery 中搜索相关主题。但是我没有看到任何方法来解决我的问题。

$(document).ready(function(){
    $("#inputForm").submit(function(event){
        $(":text").each(function() {
            var inputText = $(this).val();
            var userList = [];
            var weblink = 'http://test.com';

            // problem is from here.
            $.getJSON(weblink, function(data){
                alert(weblink); // this statement doesn't show up
                $.each(data, function(entryIndex, entry){
                    userList.push(entry['from_user']);
                });
            });
            alert(userList);
        });
     });
});

There are four problems here:

这里有四个问题:

  1. Why the first alert('weblink') doesn't show up.
  2. Why this code can't get the json data from website
  3. The goal of this code is to get the from_user tag from json file and store into userList array.
  4. The variables in "$.each(data, function(entryIndex, entry){" statement, the function have two input parameters one is entryIndex and other is entry, I am so wonder these two parameter is for what? and how can I use these two paramenters.
  1. 为什么第一个警报('weblink')没有出现。
  2. 为什么此代码无法从网站获取 json 数据
  3. 此代码的目标是从 json 文件中获取 from_user 标签并存储到 userList 数组中。
  4. “$.each(data, function(entryIndex, entry){”语句中的变量,该函数有两个输入参数,一个是entryIndex,另一个是entry,我很想知道这两个参数是做什么用的?我该如何使用这两个参数。

Can anyone help me solve this problem. I have been stock in here for one day. Thank you very much.

谁能帮我解决这个问题。我已经在这里存货一天了。非常感谢。

回答by T.J. Crowder

A couple of issues there:

有几个问题:

  1. getJSONdoes an ajax request. Ajax requests are subject to the Same Origin Policy. Unless your page is loaded from http://test.com(or a couple of other caveats), it won't work. You're probably looking for JSON-P(which jQuery also supports), provided the server supports it.

  2. getJSON, like all ajax requests, is asynchronousby default, so your second alert (with the user list) will happen beforethe request completes. Although you can make ajax requests synchronous, it's a very bad idea (locks up the UI of most browsers during the request). Instead, just use the user list after you've received it in the callback, rather than trying to use it in the function calling getJSON.

  1. getJSON做一个ajax请求。Ajax 请求受同源策略的约束。除非您的页面是从http://test.com(或其他几个警告)加载的,否则它将无法工作。您可能正在寻找JSON-P(jQuery 也支持),前提是服务器支持它。

  2. getJSON与所有 ajax 请求一样,默认情况下是异步的,因此您的第二个警报(带有用户列表)将请求完成之前发生。虽然你可以让ajax请求同步,但这是一个非常糟糕的主意(在请求期间锁定大多数浏览器的UI)。相反,只需在回调中收到用户列表后使用它,而不是尝试在函数调用中使用它getJSON

Edit: You've said below that you're trying to use the Twitter search API. That API doessupport JSON-P, so if you use JSON-P to do your request, it should work. e.g.:

编辑:您在下面说过您正在尝试使用 Twitter 搜索 API。该 API确实支持 JSON-P,因此如果您使用 JSON-P 来处理您的请求,它应该可以工作。例如:

$(document).ready(function(){
    $("#inputForm").submit(function(event){
        $(":text").each(function() {
            var inputText = $(this).val();
            var userList = [];
            var weblink = 'http://search.twitter.com/search.json?q=&ands=google';

            // problem is from here.
            $.ajax({
                url:        weblink,
                dataType:   "jsonp", // <== JSON-P request
                success:    function(data){
                    alert(weblink); // this statement doesn't show up
                    $.each(data.result, function(entryIndex, entry){ // <=== Note, `data.results`, not just `data`
                        userList.push(entry['from_user']); // <=== Or `entry.from_user` would also work (although `entry['from_user']` is just fine)
                    });
                    alert(userList); // <== Note I've moved this (see #2 above)
                }
            });
        });
     });
});

...but surely you don't want to do that for eachtext field in the form?

...但您肯定不想为表单中的每个文本字段都这样做吗?

Here's a live examplebut without a form (and only doing one request, not a request for each field).

这是一个实时示例,但没有表单(并且只执行一个请求,而不是对每个字段的请求)。

回答by nagisa

Just add to link

只需添加到链接

&callback=?

or

或者

?callback=?

(if it's first and only GET variable) This will make your call into JSONP call, which doesn't have problems with Same Origin Policy.

(如果它是第一个也是唯一的 GET 变量)这将使您的调用进入 JSONP 调用,这不会有同源策略的问题。

回答by JayD

Are you using MVC platform? Apparently, by default MVC 2.0 blocks GET requests to actions that return a JsonResult. Check out:

您使用的是 MVC 平台吗?显然,默认情况下,MVC 2.0 会阻止对返回 JsonResult 的操作的 GET 请求。查看:

http://mhinze.com/2010/04/13/json-hiHymaning-in-asp-net-mvc-2/

http://mhinze.com/2010/04/13/json-hiHymaning-in-asp-net-mvc-2/

I had the same problem whilst upgrading an existing application (written in MVC v1) that used .getJSON calls to pull data from MVC Controller to View (via jquery/javascript) & could not figure out why they did not work I tried different versions of jquery with no luck, then I found the above link. I changed to POST instead (and also changed slightly how the data was sent from the Controller - used Dictionary ) and got it working - finally!!

我在升级一个现有的应用程序(用 MVC v1 编写)时遇到了同样的问题,该应用程序使用 .getJSON 调用将数据从 MVC 控制器拉到视图(通过 jquery/javascript)并且无法弄清楚为什么它们不起作用我尝试了不同版本的jquery 没有运气,然后我找到了上面的链接。我改为 POST (并且还稍微改变了从 Controller 发送数据的方式 - 使用 Dictionary )并让它工作 - 最后!

Good luck! JayD

祝你好运!杰德

回答by Chris

Not sure but doesn't it require get arguments? Try this:

不确定,但它不需要获取参数吗?尝试这个:

$.getJSON(weblink, {}, function(data){

回答by raphie

I would like to add another reason why jQuery.getJSON() might not response as expected in a developing environment under IIS for Windows.

我想添加另一个原因,为什么 jQuery.getJSON() 在 IIS for Windows 下的开发环境中可能无法按预期响应。

Following all the procedures provided here, I was not able to get any data from a *.json file, only if I changed the extension to *.js, the response status returned

按照此处提供的所有程序,我无法从 *.json 文件中获取任何数据,只有将扩展名更改为 *.js,才会返回响应状态

{"status"="404", "statusText"="Not Found"}

Then I remembered that with IIS there are some MIME/Types that are not specified. Adding MIME/Type application/json for files with extension .json solved my problem.

然后我想起 IIS 有一些未指定的 MIME/类型。为扩展名为 .json 的文件添加 MIME/Type application/json 解决了我的问题。

For information how to add MIME/types on iis7.

有关如何在 iis7 上添加 MIME/类型的信息。