dongyanjing5975 2018-05-20 16:06
浏览 802
已采纳

在AJAX中使用post传递文本框数据的正确方法

Right now I am using this, and it works perfectly, but for some reason I don't think this is the best or most efficient way to accomplish this task. It seems like it will get messy as I start to add more textbook inputs. Please review:

index.html:

function saveUserData(userData) {
  $.post('userData.php', {
    textbox1: document.getElementById('textbox1').value,
    textbox2: document.getElementById('textbox2').value, 
    userData: JSON.stringify(userData)
  }, function(data) {
    return true; 
  });

html:

<input name="textbox1" type="textbox1" id="textbox1">
<input name="textbox2" type="textbox2" id="textbox2">

userdata.php:

$userData = json_decode($_POST['userData']);
$textbox1 = $_POST['textbox1'];
$textbox2 = $_POST['textbox2'];
//Insert user data
$query = "INSERT INTO users SET first_name = '".$userData->first_name."', last_name = '".$userData->last_name."', email = '".$userData->email."', picture = '".$userData->picture->data->url."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."',test1 = '".$textbox1."',test2 = '".$textbox2."' ";
$insert = $db->query($query);
  • 写回答

1条回答 默认 最新

  • dqdpz60048 2018-05-20 16:31
    关注

    EDIT: Ok, how about something like this?

    //javascript
    var toPost = {};
    $("input").each(function() {
        toPost[$(this).attr('name')] = $(this).val()
    });
    
    var inputs = JSON.stringify(toPost);
    //send postJSON to php with $.post()
    
    //in php
    $inputs = json_decode($_POST["inputs"], true);
    //now all the inputs can be accessed
    foreach ($inputs as $name => $val) {
         echo "input with name '$name' has value $val";
         //you can do all you prepared statements and stuff with these values.
    }
    

    Much more general and will automatically convert your inputs to a json object with the name of the input used as the key. Don't use $(":input") as this will include things like buttons.

    --- OLD ANSWER: ---

    Can't really test this right now, but could you do something like:

    //javascript:
    var i = 1;
    while ($('#textbox'+i).length != 0) {
        postObject['textbox'+i] = $('#textbox'+i).val();
        i++;
    }
    //postObject values are then added to the $.post call
    
    //php:
    $i = 1;
    $query = "INSERT INTO users SET first_name = '".$userData->first_name."', last_name = '".$userData->last_name."', email = '".$userData->email."', picture = '".$userData->picture->data->url."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
    while (isset($_POST["textbox$i"])) {
        $query .= ", test$i = '".$_POST["textbox$i"]."'";
        $i++;
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部