2018-05-21 00:06
浏览 235


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:


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


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


$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
    dqdpz60048 2018-05-21 00:31

    EDIT: Ok, how about something like this?

    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:

    var i = 1;
    while ($('#textbox'+i).length != 0) {
        postObject['textbox'+i] = $('#textbox'+i).val();
    //postObject values are then added to the $.post call
    $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"]."'";
    点赞 评论