我正在构建一个 Google Chrome 浏览器扩展,它使用 $.ajax
请求将数据从网页发送到我的服务器(目前使用 localhost 托管)。在扩展有权访问的网页 ( more on content scripts) 上下文中执行的 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(即 uploadddddendpoint.php)时,$.ajax
的 error中的代码
参数被执行。
我读过类似的问题,例如 jQuery $.ajax response empty, but only in Chrome但无济于事...
更新:
我完全删除了无效的第二个 type: "jsonp"
参数并添加了 dataType: "text/html"
。每次运行代码时,我现在都会收到失败的 ajax
请求。
更新:奇怪地将 dataType : "text/html"
更改为 dataType : "html"
会导致 ajax
请求成功,但再次使用空白 data
变量。
更新:当使用开发工具包监控网络 XHR 时,这些是已发送/响应的消息:
关于可能重复的标志 Impossible to cross site ajax api calls in a chrome extension?我建议否则!我已经调查了那个问题,但问题似乎并不相同。
最佳答案
为什么您的 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");
}
});
您可以看到我将 URL 替换为 /quartzsite/uploadendpoint.php
。这可能会解决问题...绝对 URL 可能表示跨域请求,这不是您想要的。
此外,作为旁注,没有必要设置 contentType,因为您设置的内容已经是默认值。如果您要发送 JSON 或 XML,那么您需要设置 contentType。
关于javascript - Ajax 请求成功但结果为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243319/