$ .getJSON无效

Jim*_*Lin 7 jquery getjson

我在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);
        });
     });
});
Run Code Online (Sandbox Code Playgroud)

这里有四个问题:

  1. 为什么第一个警报('weblink')没有出现.
  2. 为什么这段代码无法从网站获取json数据
  3. 此代码的目标是从json文件获取from_user标记并存储到userList数组中.
  4. 变量在"$ .each(data,function(entryIndex,entry){"语句中,该函数有两个输入参数,一个是entryIndex,另一个是entry,我很奇怪这两个参数是针对什么的?我怎么用这两个参数.

任何人都可以帮我解决这个问题.我在这里待了一天.非常感谢你.

T.J*_*der 15

那里有几个问题:

  1. getJSON做一个ajax请求.Ajax请求受同源策略的约束.除非您的页面被加载http://test.com(或其他一些警告),否则它将无效.你可能正在寻找JSON-P(jQuery也支持),只要服务器支持它.

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

编辑:您在下面说过,您正在尝试使用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)
                }
            });
        });
     });
});
Run Code Online (Sandbox Code Playgroud)

...但是你肯定不想为表单中的每个文本字段执行此操作?

这是一个实例,但没有表单(只做一个请求,而不是每个字段的请求).