使用Ajax发送序列化数据和其他数据

时间:2016-07-07 15:14:27

标签: javascript ajax

我正在尝试使用ajax帖子和一些其他数据发送序列化数据。我尝试了以下方式:

$("#prw").on('click', function(e){

    var url = window.location.origin + "/newsletter/preview";

    var title = $('#title').val();
    var intro = $('#intro').val();
    var array = table.$('input[type="checkbox"], input[type="text"]').serialize() + "&title=" + title + "&intro=" + intro;

    $.ajax({
        type: "POST",
        url: url,
        data: array
    }).done(function(data){
        console.log("Response", data);
    });

    e.preventDefault();
});

但它只显示复选框和文本,而不是响应中的标题和介绍。 我也尝试过这种方法:

$("#prw").on('click', function(e){

    var url = window.location.origin + "/newsletter/preview";

    var title = $('#title').val();
    var intro = $('#intro').val();
    var array = table.$('input[type="checkbox"], input[type="text"]').serializeArray();
    array.push({name: 'title', value: title});
    array.push({name: 'intro', value: intro});    

    $.ajax({
        type: "POST",
        url: url,
        data: array
    }).done(function(data){
        console.log("Response", data);
    });

    e.preventDefault();
});

它也不起作用。这个URL转到CodeIgniter控制器:

function preview() {
    $post = $this->input->post();
    print_r($_POST);
    return $post;
}

2 个答案:

答案 0 :(得分:0)

创建对象要容易得多:

var url = window.location.origin + "/newsletter/preview";
var data = { title: $('#title').val() , intro : $('#intro').val() };
// I don't know what you table is.. 
// if you tell me the plugin I can help sending that that either

$.ajax({
    type: "POST",
    url: url,
    data: $.param(data)
}).done(function(data){
    console.log("Response", data);
});

答案 1 :(得分:0)

首先,请注意答案可能会有所不同,具体取决于API端点的期望。你能告诉我们你想要达到的控制器/方法吗?

话虽如此,我猜测端点需要一个JSON对象(可能是字符串化的)。

根据这些假设,请尝试以下方法:

<form #f="ngForm">
  <custom-input name="Nan" [ngModelOptions]="{name: 'custom'}" ngModel>
</form>

});

相关问题