javascript - ajax问题求助

查看:147
本文介绍了javascript - ajax问题求助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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
    }
}

服务开了之后打开后报错

谷歌的跨域我也整了 还是不行?怎么回事啊?

解决方案

错误信息写的很明白了,跨域请求只支持几种协议,file协议并不支持。你可以把自己的项目用文件服务器托管一下,走网络请求就ok了。

这篇关于javascript - ajax问题求助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆