Javascript 如何使用get或post方法连接和执行ajax?
我有这个JQuery代码,但它没有成功,总是给出以下内容:Javascript 如何使用get或post方法连接和执行ajax?,javascript,jquery,ajax,node.js,google-chrome,Javascript,Jquery,Ajax,Node.js,Google Chrome,我有这个JQuery代码,但它没有成功,总是给出以下内容: XMLHttpRequest cannot load http://localhost:8080/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access. (17:21:10:896 | error, java
XMLHttpRequest cannot load http://localhost:8080/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access. (17:21:10:896 | error, javascript)
at win_1.html
Error: undefined (17:21:10:902)
at win_1.html:18
Debugging session with browser was closed.
index.html:
<script src=http://code.jquery.com/jquery-1.11.2.min.js ></script>
<body>
response here: <p id="lblResponse">fill me in</p>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'http://localhost:8080',
// dataType: "jsonp",
data: '{"data": "TEST"}',
type: 'POST',
//jsonpCallback: 'callback', // this is not relevant to the POST anymore
success: function (data) {
var ret = jQuery.parseJSON(data);
$('#lblResponse').html(ret.msg);
console.log('Success: ')
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
$('#lblResponse').html('Error connecting to the server.');
},
});
});
</script>
</body>
在您的
console.log()之后添加以下内容:
log('收到请求:');
如果(请求方法==='OPTIONS'){
//添加所需的标题
var头={};
头文件[“访问控制允许源文件”]=“*”;
标题[“访问控制允许方法”]=“发布、获取、放置、删除、选项”;
标头[“访问控制允许凭据”]=true;
标题[“访问控制最大年龄”]=“86400”;//24小时
headers[“Access Control Allow headers”]=“X-Requested-With,Access Control Allow-Origin,X-HTTP-Method-Override,内容类型,授权,接受”;
//回应请求
文件标题(200,标题);
res.end();
}否则{
//代码的其余部分
}
资料来源:
相同来源的可能副本需要相同的协议、相同的主机和相同的端口号。您的端口号不同;8080对8383。请记住,如果显式指定默认端口号,可能还需要在ajax URL中显式指定该端口号,这使它们成为不同的域。浏览器说它正在运行的javascript是从localhost:8383
下载的。这不太可能是浏览器错误。尤其是因为节点服务器代码无法为静态资产(如您引用的index.html)提供服务。要查看此页面,您要转到哪个URL?有一个详细的标志。不过,我强烈建议您在可能的重复链接中添加标题。关闭chrome的安全功能是非常危险的。设置该标志后,您访问的任何站点都可以访问您登录到的任何服务中的所有数据。非常好。这就是问题的答案。而不是负投票。非常感谢,切中要害。
var http = require('http');
var util = require('util')
http.createServer(function (req, res) {
console.log('Request received: ');
util.log(util.inspect(req))
// this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url)
// this line logs just the method and url
res.writeHead(200, { 'Content-Type': 'text/plain' });
req.on('data', function (chunk) {
console.log('GOT DATA!');
});
res.end('callback(\'{\"msg\": \"OK\"}\')');
}).listen(8080);
console.log('Server running on port 8080');