form表单提交跨域(jquery方式)

因为是post方式,所以jsonp的方法不可以,只能模拟表单提交,因为要取到response数据,所以要用到ajaxform
原生js写法

// 模拟post表单
$.extend({
    StandardPost:function(url,args){
        var body = $(document.body),
            form = $("
"), input; form.attr({"action":url}); $.each(args,function(key,value){ input = $(""); input.attr({"name":key}); input.val(value); form.append(input); }); form.appendTo(document.body); document.body.removeChild(form[0]); return form; } });
// 获取到form
var form = $.StandardPost('http://192.168.0.xxx:8888/',{
        product_code: 'CLZ7',
        type: '1',
        start: '20170815143000000',
        end: '20170817154000000'
    });
// 使用ajaxsubmit提价  设置submit之后的操作
var options = {
        target: '#output',          //把服务器返回的内容放入id为output的元素中
        beforeSubmit: showRequest,  //提交前的回调函数
        success: showResponse,      //提交后的回调函数
        //url: url,                 //默认是form的action, 如果申明,则会覆盖
        //type: type,               //默认是form的method(get or post),如果申明,则会覆盖
        //dataType: null,           //html(默认), xml, script, json...接受服务端返回的类型
        //clearForm: true,          //成功提交后,清除所有表单元素的值
        //resetForm: true,          //成功提交后,重置所有表单元素的值
        //timeout: 3000               //限制请求的时间,当请求大于3秒后,跳出请求
    };
    function showRequest(data) {
        console.log('showRequest',data)
    }
    function showResponse() {
        var data = $('#output').html();
        var json = JSON.parse(data);
        var response_content = JSON.parse(json.response_content);
        console.log('showResponse',json,response_content);
    }
    form.ajaxSubmit(options);

你可能感兴趣的:(form表单提交跨域(jquery方式))