form表单提交跨域(原生js)

因为是post方式,所以jsonp的方法不可以,只能模拟表单提交
如果依赖jquery的话可以参考jquery版本 form表单提交跨域(jquery方式)

首先模拟form表单

// 模拟form表单
function StandardPost(url,args){
    var body = document.body,
        form = document.createElement('form'), 
        input;
        
    form.setAttribute('action',url);
    for(var key in args){
        input = document.createElement('input');
        input.setAttribute('type','hidden');
        input.setAttribute('name',key);
        input.setAttribute('value',args[key]);
        form.appendChild(input);
    }
    document.body.appendChild(form)
    document.body.removeChild(form);
    return form;
}

// 获取form表单方式
var form = StandardPost('http://106.14.6.153:8888/',{
    product_code: 'SIZ7',
    type: '1'
});

通过原生Ajax提交数据

function submitData(form){
    var xhr = createXHR();  // 创建XHR对象
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
                var result = JSON.parse(xhr.responseText);
                console.log('success',result);
            }else{
                console.log('error',xhr.status);
            }
        }
    }
    url = form.getAttribute('action');
    xhr.open('POST',url,true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send(serialize(form));   // 序列化表单
}

ajax请求所需要的创建XHR对象 (兼容性写法)

    // 创建XHR对象
    function createXHR(){
        if(typeof XMLHttpRequest != 'undefined'){
            return new XMLHttpRequest();
        }else if(typeof ActiveXObject != 'undefined'){
            if(typeof arguments.callee.activeXString != 'string'){
                var version = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", " MSXML2.XMLHttp"],
                    i,len;
                
                for(i = 0,len = version.length; i

序列化表单

// 表单序列化
    function serialize(form){
        var parts = [],
            field = null,
            i,len,j,optLen,option,optValue;
        
        for(i = 0, len = form.elements.length; i < len; i++){
            field = form.elements[i];
            switch(field.type){
                case 'select-one':
                case 'select-multiple':
                    if(field.name.length){
                        for(j = 0 ,optLen = field.options.length; j < optLen; j++){
                            option = field.options[j];
                            if(option.selected){
                                optValue = '';
                                if(option.hasAttrbute){
                                    optValue = (option.hasAttrbute('value') ? option.value : option.text);
                                }else{
                                    optValue = (option.attributes['value'].specified ? option.value : option.text);
                                }
                                parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(optValue));
                            }
                        }
                    }
                    break;
                case undefined:  // 字符集
                case 'file': //文件输入
                case 'submit': //提交按钮
                case 'reset': //重置按钮
                case 'button': //自定义按钮 
                    break;
                case 'radio': //单选按钮
                case 'checkbox': // 复选框
                    if(!field.checked){
                        break;
                    }
                    // 执行默认操作
                default:
                    if(field.name.length){
                        parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value));
                    }
            }
        }
        return parts.join('&');
    }

综合使用

// 获取表单
var form = StandardPost('http://xxx.xxx.xxx:8888/',{
    product_code: 'SIZ7',
    type: '1'
});

//请求数据 
submitData(form);

你可能感兴趣的:(form表单提交跨域(原生js))