您如何在php中使用ajax发布表单?

问题描述 投票:0回答:1

我正在尝试使用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);
        }
    });
});
ajax forms ajaxform
1个回答
0
投票

关于您的代码的几个注释。

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网络选项卡,查看是否正在发送ajax请求。检查它是否到达正确的目的地,并检查服务器响应是什么。

检查所有这一切,您应该在正确的位置。

© www.soinside.com 2019 - 2024. All rights reserved.