[英]Ajax request succeeds but result is empty
我正在构建一个Google Chrome浏览器扩展程序,它使用$.ajax
请求将数据从网页发送到我的服务器(目前使用localhost托管)。 在扩展程序有权访问的网页上下文( 更多内容脚本 )中执行的content_script.js
文件运行此代码:
//note: encode64String is assigned earlier in the script...
$.ajax({
type: "POST",
url: "http://localhost:8888/quartzsite/uploadendpoint.php",
type: "jsonp",
data: {img: encode64String},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data){
console.log("The ajax request succeeded!");
console.log("The result is: ");
console.log(data);
},
error: function(){
console.log("The request failed");
}
});
问题是Ajax
请求成功但它返回的data
参数是空的...
运行代码后控制台如下所示:
目前uploadedendpoint.php
文件的内容是:
<?php
header("Access-Control-Allow-Origin: *");
echo 'This comes from php file'; die();
?>
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......
</body>
</html>
这意味着data
变量中至少应该返回一些内容。
我进一步确认请求是成功的,因为当我将请求发送到损坏的url(即uploaddddddendpoint.php)时, $.ajax
的error
参数中的代码被执行。
我已经读过像jQuery $ .ajax响应空类似的类似问题,但仅限于Chrome但无济于事......
更新 :
我已经删除了无效的第二种type: "jsonp"
参数完全添加了dataType: "text/html"
。 我每次运行代码时都会收到失败的ajax
请求。
更新 :奇怪地改变dataType : "text/html"
到dataType : "html"
导致ajax
请求成功,但再次使用空白data
变量。 更新 :使用dev工具包监视网络XHR时,这些是发送/响应消息:
关于可能重复到不可能跨越网站的标志ajax api调用chrome扩展? 我建议不然! 我调查了这个问题,问题似乎并不相同。
为什么AJAX请求中有两个type
字段? jsonp
和POST
。
$.ajax({
type: "POST", // OK
url: "http://localhost:8888/quartzsite/uploadendpoint.php",
type: "jsonp", // ???
// ...
});
更新:
我认为你应该使用URL的相对路径。 尝试将您的请求更改为以下内容:
$.ajax({
type: "POST",
url: "/quartzsite/uploadendpoint.php",
dataType: "text/html",
data: {img: encode64String},
success: function(data){
console.log("The ajax request succeeded!");
console.log("The result is: ");
console.dir(data);
},
error: function(){
console.log("The request failed");
}
});
您可以看到我用/quartzsite/uploadendpoint.php
替换了URL。 这可能会解决问题......绝对URL可能会发出跨域请求的信号,这不是您所追求的。
另外,作为旁注,不必设置contentType,因为您设置的内容已经是默认值。 如果您要发送JSON或XML,那么您需要设置contentType。
解决问题的一种方法:在Chrome中是一个空洞的答案。 在FF中显示一个PHP警告在答案警告:....在线...
删除警告后,chrome开始显示响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.