weixin_33711641 2014-10-11 17:47 采纳率: 0%
浏览 2

ajax呼叫发送帖子

I have a small function that will eventually save to a database, but um having trouble reading the post into the php, here is the jquery:

$("#loginbtn").click(function() {

        var myData = new Array(
          'emp='+ $("#emp").val(), //build a post data structure
          'sdate='+ $("#sdate").val(),
          'tdate='+ $("#tdate").val(),
          'address='+ $("#address").val(),
          'city='+ $("#city").val(),
          'state='+ $("#state").val(),
          'zip='+ $("#zip").val(),
          'pos='+ $("#pos").val(),
          'sal='+ $("#sal").val(),
          'phone='+ $("#phone").val(),
          'sname='+ $("#sname").val(),
          'duties='+ $("#duties").val(),
          'reason='+ $("#leave").val()
        );
        alert(myData)
        jQuery.ajax({
        type: "POST", // HTTP method POST or GET
        url: "inc/functions.php", //Where to make Ajax calls
        dataType:"Data", // Data type, HTML, json etc.
        data:myData, //Form variables
        success:function(data){
            alert('back')
         },
        error:function (xhr, ajaxOptions, thrownError){
            alert(thrownError);
        }
        });
    });

it will display that it came back but of course the error is that the fields are null. any help appreciated. Jeff

  • 写回答

2条回答 默认 最新

  • weixin_33736048 2014-10-11 17:52
    关注

    The way you are sending data to the server is not correct. The better way to do it is to use form serialization:

    $("#loginbtn").click(function () {
    
        //build a post data structure
        var myData = $('#login-form').serialize();
        alert(myData)
        jQuery.ajax({
            type: "POST", // HTTP method POST or GET
            url: "inc/functions.php", //Where to make Ajax calls
            dataType: "Data", // Data type, HTML, json etc.
            data: myData, //Form variables
            success: function (data) {
                alert('back');
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(thrownError);
            }
        });
    });
    

    For this to work, make sure all you input fields have name attributes, like emp, sdate, etc. Then on server side you will be able to read POST parameters like this

    $_POST['emp']
    

    The problem with your approach is that when you provide just an array there is no keys corresponding to values, and that's why you can't read nothing in PHP.

    评论

报告相同问题?