【问题标题】:jQuery Ajax - can't get a responsejQuery Ajax - 无法得到响应
【发布时间】:2012-03-10 23:05:47
【问题描述】:

我正在使用这个 jQuery.ajax:

var url = "http://client.my_url.com/test_get_account_data.php";  
jQuery.ajax({
    type: "GET",
    url: url,
    cache: false,
    success: function(resultsData){
        alert("We're finally making the call.");
    },
    error:function (jqXHR, textStatus, errorThrown){
        alert("Error:" + textStatus+ "," + errorThrown);
    } 
});

点击这个 php 脚本:

<?php
header("Content-Type: text/plain");

$myFile = "LogFile.log";
$fh = fopen($myFile, 'w');

$accountJSON = array("id"=>"Level 3.accountName","type"=>"Level 3","name"=>"accountName","total"=>"1059.25","in"=>"8603.56","out"=>"7544.31");

$encodedResponse = json_encode($accountJSON);

fwrite($fh, "We're at the end of get_account_data with encodedResponse:\n");
fwrite($fh, $encodedResponse."\n");

echo $encodedResponse;
?>

但由于某种原因,我从来没有成功过。我已经尽可能地简化了这一点,但它仍然失败了。在日志中,我有输出:

We're at the end of get_account_data with encodedResponse:<br/>
{"id":"Level 3.accountName", "type":"Level 3", "name":"accountName", "total":"1059.25", "in":"8603.56", "out":"7544.31"}

有人有什么建议吗?我认为这会很容易......也许是这样,而我只是在做一些愚蠢的事情。

谢谢

【问题讨论】:

  • 您的浏览器的 Javascript 错误控制台说什么?
  • 您的网页是否与 PHP 服务器在同一个域中?您的浏览器的错误控制台或调试控制台是否报告任何 javascript 错误或安全错误?
  • 试过header("Content-Type: application/json");?你实际上并没有发回纯文本,是吗?
  • 不要使用完整的 url 只需使用 /dir/a/b/c/file.php 如果您使用 chrome,请检查日志
  • Javascript 错误控制台 (firefox) 没有错误。有警告,但这些似乎都来自 jquery-ui css 问题。 firebug 中的 net 选项卡的请求标头有:GET /test_get_account_data.php?_=1331419975860 HTTP/1.1 主机:client.sweepscoach.com 用户代理:Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:10.0。 2) Gecko/20100101 Firefox/10.0.2 Accept: / Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: localhost:8080/SCSalesDataReport/test/…来源:localhost:8080

标签: php json jquery


【解决方案1】:

您似乎正在尝试使用来自http://localhost:8080 的 AJAX GET 请求调用 http://client.my_url.com

根据浏览器的same origin policy,您不能将 AJAX GET/POST 请求发送到另一个域。跨域 AJAX 需要使用JSONP

【讨论】:

  • 我可以以纯文本格式进行传输吗? JSONP 不允许非异步调用,而我需要进行的调用之一需要它。我进行了更改,以便响应标头具有:“Content-Type:text/plain”,并且我在 ajax 调用中添加了“dataType:'text'”参数,但它似乎仍然没有返回任何内容。 :(
  • 我承认让 JSONP 工作所花费的时间比我愿意承认的要长得多,但现在可以了。如果其他人最终遇到这个问题,请到这里查看更多演练:fbloggs.com/2010/07/09/…geekality.net/2010/06/27/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
  • 2014-06-06
  • 1970-01-01
相关资源
最近更新 更多