ajax({
url : 'json2.json',
type: 'get',
dataType : 'json',
success : function(text){alert(responseText);},
fail : function(status){alert(status);}
});
function ajax(options){
options = options || {};
options.type = (options.type || 'get').toUpperCase();
options.dataType = options.dataType||'json';
options.data = {"name":"dzxczx","phone":188};
var params = formParams(options.data);
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else if(window.ActiveXObject){
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}else{
throw new Error('Your browser does not support XHR');
}
if(options.type == 'GET'){
xhr.open('GET',options.url + '?' + params,true);
xhr.send(null);
}else if(options.type == 'POST'){
xhr.open('POST',options.url,true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(params);
}
xhr.onreadyStatechange = function(){
if(xhr.readyState == 4){
var status = xhr.status;
if(status >= 200 && status < 300){
options.success && options.success(xhr.responseText);
}else{
options.fail && options.fail(status);
}
}
}
function formParams(data){
var arr = [];
for(var name in data){
arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
arr.push(('v='+Math.random()).replace('.',''));
return arr;
}
}
url
{
"name": "kitty",
"sex": "female",
"age": 3,
"siblings": {
"name": "hello",
"sex": "male",
"age": 4
}
}
服务开了之后打开后报错
谷歌的跨域我也整了 还是不行?怎么回事啊?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
错误信息写的很明白了,跨域请求只支持几种协议,
file协议并不支持。你可以把自己的项目用文件服务器托管一下,走网络请求就ok了。使用一下CORS 解决跨域问题吧,在后台请求的header上加上一小段配置就好了
我们项目是node写到,所以下面是这样的,给你参考一下
请求Ajax不能直接访问文件,需要开启一个静态服务器来访问文件,如用Apache
本地启动web服务,把代码放上去再调试吧~
谢邀。不过楼上已经回答得差不多了。
我是前后端一起开发,所以直接用 VS 启动 IISExpress。
如果你是纯前端开发,而且是基于静态的 json 来调试,建议你搭个 Nginx,如果以后和后端联调,还可以用 Nginx 做反向代理,比较方便的
参考:http://jamesfancy.blog.51cto.com/2516291/1394935