Bra*_*non 6 html javascript ajax jquery google-chrome-extension
我正在构建一个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");
}
});
Run Code Online (Sandbox Code Playgroud)
问题是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>
Run Code Online (Sandbox Code Playgroud)
这意味着data变量中至少应该返回一些内容.
我进一步确认请求成功,因为当我将请求发送到损坏的url(即uploaddddddendpoint.php)时,执行$.ajaxs error参数内的代码.
我已经读过像jQuery $ .ajax响应空类似的类似问题,但仅限于Chrome但无济于事......
更新:
我完全删除了无效的第二个type: "jsonp"参数并添加了dataType: "text/html".我ajax每次运行代码时都会收到一个失败的请求.
更新:奇怪地改变dataType : "text/html"以dataType : "html"使ajax请求成功,但再次使用空白data变量.
更新:使用dev工具包监视网络XHR时,这些是发送/响应消息:

关于可能重复到不可能跨越网站的标志 ajax api调用chrome扩展?我建议不然!我调查了这个问题,问题似乎并不相同.
type为什么AJAX 请求中有两个字段?jsonp和POST。
$.ajax({
type: "POST", // OK
url: "http://localhost:8888/quartzsite/uploadendpoint.php",
type: "jsonp", // ???
// ...
});
Run Code Online (Sandbox Code Playgroud)
更新:
我认为您应该使用 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");
}
});
Run Code Online (Sandbox Code Playgroud)
你可以看到我将 URL 替换为/quartzsite/uploadendpoint.php。这可能会解决问题...绝对 URL 可能会发出跨域请求的信号,而这不是您想要的。
另外,顺便说一下,没有必要设置 contentType,因为您设置的内容已经是默认值。如果您要发送 JSON 或 XML,那么您需要设置 contentType。