您如何 post 在 php 中使用 ajax 的表格?

How do you post a form with ajax in php?

我正在尝试使用 ajax 提交表单,但我设置了它,当它成功时应该显示 jquery 警报,但它没有显示,所以我认为它不成功。大家知道为什么吗??

这是我尝试使用 ajax

提交的表单
<b>Product Title: </b><br><input style="width: 50%;" class="form-control itemtitle" type="text" name="title" required="true"><br>
<b>Product Description: </b><br><input style="width: 50%;" class="form-control itemdescription" type="text" name="description" required="true"><br>
<b>Product Price: </b><br><input style="width: 50%;" class="form-control itemprice" type="number" name="price" required="true"><br>
<b>Product Image Address: </b><br><input style="width: 50%;" class="form-control itemimageaddress" type="text" name="image" required="true"><br>
<button type="submit" class="btn btn-primary createproductsubmit">Create Product</button>

这是我正在使用的ajax

$(".createproductsubmit").click(function(){
    var itemtitle = $(".itemtitle").val();
    var itemdescription = $(".itemdescription").val();
    var itemprice = $(".itemprice").val();
    var itemimageaddress = $(".itemimageaddress").val();

    var dataString = "itemtitle=" + itemtitle + "&itemdescription=" + itemdescription + "&itemprice=" + itemprice + "&itemimageaddress=" + itemimageaddress;

    $.ajax({
        type: "POST",
        url: "pages/newproductaction.php",
        data: dataString,
        cache: false,
        success: function(result)
        {
            alert(result);
        }
    });
});

对您的代码的一些评论。

1) 您应该用 <form> 标记围绕表单输入和按钮元素。 2) 不是通过 POST 请求传递字符串,而是像这样传递一个对象:

data: {
    itemtitle: itemtitle,
    itemdescription: itemdescription,
    itemprice: itemprice,
    itemimageaddress: itemimageaddress
}

3) alert() 不是 jquery 函数,而是一个纯 javascript 函数。我建议您使用 console.log() 并在控制台中查看输出。

4) 检查控制台是否存在可能的 javascript 错误。如果出现 js 错误,代码甚至不会触发 ajax 调用。

5) 检查 Dev tools Network 选项卡,查看是否正在发送 ajax 请求。检查它到达正确的目的地并检查服务器响应是什么。

检查所有这些你应该在正确的路径。

只需简单地使用

$.post("pages/newproductaction.php", {
itemtitle: itemtitle,
itemdescription: itemdescription,
itemprice: itemprice,
itemimageaddress: itemimageaddress
}, function(data){

});