【问题标题】:Can't use $.get to get data from another domain不能使用 $.get 从另一个域获取数据
【发布时间】:2014-04-10 19:14:48
【问题描述】:

在我的 localhost 中,我创建了一个 Web 应用程序来从网站获取数据,它只包含一个字符。所以我创建了这个:

$.get("http://www.website.web.id/data.txt", function(client_req) { 
alert(client_req); 
});

但它无法加载数据。为什么?

【问题讨论】:

标签: jquery web


【解决方案1】:

这可能是您的解决方案。见:

crossdomain.xml for jQuery?

我建议为此使用 JSON —— 我知道这听起来可能不是一个快速简单的解决方案,但它是最好的解决方案。

如果你使用 PHP,你可以这样做:

<?php
   $arr = array('example' => 'example data', 'anotherexample' => 'OK', 'userage' => 13);
   echo json_encode($arr);
?>

它会以 JSON 格式输出数据。然后在您的 jQuery 中,您会执行以下操作:

$.getJSON('http://www.website.web.id/data.php', function(client_req) {
        alert(client_req.example);
        alert(client_req.anotherexample);
        alert(client_req.userage);
    }
});

希望这能让您朝着正确的方向前进。

【讨论】:

  • 对不起,我是新来的,声望不够。 :)
【解决方案2】:

是的,跨域问题,你可以使用 JSONP 或 CORS 来解决这个问题,我已经多次发过这个问题:

JQuery JSON Calls To PHP WebService Always Runs "Error" Callback

Is there any physical, readable difference between a JSON string and a JSONP string?

【讨论】:

  • 谢谢。我现在正在改变我的方法。
  • 对不起,我是新来的,声望不够。 :)
猜你喜欢
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
  • 2012-01-25
  • 2019-05-02
  • 1970-01-01
  • 2013-03-26
相关资源
最近更新 更多