为什么 $.get() 无法正常工作


Why is $.get() not working properly

我正在尝试从php文件中检索一行代码。我的代码如下:

$( document ).ready(function() {
    alert("1");
    $.get('http://myurl.com/toolbox/myPHP.php?store_id=4649b4a8a802c3&couponShow=checkout', function(data) {
        alert(data);
        alert("2");
    });
});   
window.onload = function() {
    if (window.jQuery) {
        // jQuery is loaded
        alert("Yeah!");
    } else {
        // jQuery is not loaded
        alert("Doesn't Work");
    }
}

"1""Yeah!"都得到了正确的警报,所以jQuery正在加载,但我无法进入get函数。访问内部的 URL 会返回完全预期的内容。我在这里做的事情有什么问题吗?我可以采取哪些步骤来查找问题?

$( document ).ready(function() {
    alert("1");
    $.get('http://myurl.com/toolbox/myPHP.php?store_id=4649b4a8a802c3&couponShow=checkout')
     .done( function() {
        alert("2");
    }).fail(function(){
        alert("3") ;
    });
});

请参阅 Jquery $。获取

尝试在请求末尾使用 .fail() 来确定它是否是关于 php 文件的错误。

使用data回调接收失败请求的详细信息

这将起作用:

$.get("http://api.postcodes.io/postcodes?q=da117ne", function (data) {
  alert("it worked: " + data.status);
}).fail(function (data) {
  alert(data.statusText);
});

这不会,但会给出错误的响应

$.get("dedededhttp://api.postcodes.io/postcodes?q=da117ne", function (data) {
  alert("it worked: " + data.status);
}).fail(function (data) {
  alert(data.statusText);
});

下面是一个关于jsfiddle的例子:http://jsfiddle.net/rx6ws7hw/

我在当前页面上尝试了像这样复制/粘贴略微修改的版本(它有效):

$( document ).ready(function() {
    $.get('http://stackoverflow.com', function(data) {
        window.console.log(data);
    });
});

如果你想尝试一下,你也可以这样做。

在此页面上的 Chrome 中,按 Command+Option+I(菜单 -> 更多工具 -> 开发者工具)。单击显示的新"开发人员窗格"顶部的控制台选项卡。将上述代码粘贴到控制台中,然后按回车键。

但是,如果我稍微改变一下,

$( document ).ready(function() {
    $.get('http://google.com', function(data) {
        window.console.log(data);
    });
});

我得到这个(没有添加 .fail 进行调试):

XMLHttpRequest cannot load http://google.com/?_=1419962724028. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://stackoverflow.com' is therefore not allowed access.

我对通过跨域获取内容不是很熟悉,但也许在您自己的服务器上使用这个小测试会引导您朝着正确的方向前进。

我认为我们需要更多信息来更全面地诊断问题。

如果您已经知道所有这些:),我深表歉意我知道这很简单,但这是我开始的第一个地方。