首页 > 解决方案 > 无法使用 jQuery 和 Ajax 插入数据库

问题描述

我是 jQuery 和 ajax 的初学者。当我单击添加按钮时,所有字段都是空的。然后,我填写这些字段,当我单击提交按钮时,什么也没有发生。我不知道该怎么办。任何人都可以帮助我吗?

单击添加按钮时:

$("#add").on("click", addSeries);

function addSeries() {

    $.getJSON("http://localhost:8080/Serie/getAll", function(series) {
        series.length + 1;
        $("#txtSerieId").val(series.length + 1);
    });
}

点击提交按钮时

$("#submit").on("click", submit);
function submit() {

    var serieJson = '{"serie_id":' + $("#txtSerieId").val() + ',';
    serieJson += '"name" : "' + $("#txtName").val() + '",';
    serieJson += '"language_id" : "' + $("#txtLanguage_id").val() + '",';   
    serieJson += '"genre_id" : "' + $("#txtGenre").val() + '",';     
    serieJson += '"network_id" : "' + $("#txtNetwork").val() + '"';      
    serieJson += '}';

    $.ajax({
        method: "POST",
        url:"http://localhost:8080/Series/add",
        data: JSON.stringify(serieJson),
        dataType: "json",
        processData:false,
        headers: {
            'Content-Type': "application/json"
    },
        success: function(data) {
            getAllSeries();
        }, error: function(err) { 
        }
    });

}

标签: javascriptjquery

解决方案


创建对象而不是将值附加到字符串。

function submit() {

    var serieJson = {
        serie_id: $("#txtSerieId").val(),
        name: $("#txtName").val(),
        language_id: $("#txtLanguage_id").val(),
        genre_id: $("#txtGenre").val(),
        network_id: $("#txtNetwork").val()
    };

    $.ajax({
        method: "POST",
        url:"http://localhost:8080/Series/add",
        data: JSON.stringify(serieJson),
        dataType: "json",
        processData:false,
        headers: {
            'Content-Type': "application/json"
        },
        success: function(data) {
            getAllSeries();
        },
        error: function(err) { 
        }
    });
}

推荐阅读