dousha7904 2016-05-14 05:01
浏览 402
已采纳

如何正确传递jquery .ajax()函数的数据字符串参数?

var username = $('#username').val();

var dataString = 'username=' + username;

    $.ajax({
        type: "POST",
        url: "signinout.php",
        data: dataString,
        success: function() {
            $('.user').html('<span>Welcome <span id="loggedUser">' + username + '</span>!</span> <a id="signOut" onclick="window.location.reload()">SIGN OUT</a>');
        }
    });

using the above code, my username variable is not being passed on correctly, I'm assuming something is wrong with the way I coding the datastring parameter but I'm not sure how to do it correctly.

Below is the php code that I am using in signinout.php to insert the username into the database, the username field is not being entered with each new entry into the database.

$username = protect($_POST['username']);
$time = time();

$sql = "INSERT INTO users
    (username, join_date)
        VALUES
    ('$username', '$time')";
$result = mysqli_query($cn, $sql) or
    die(mysqli_error($cn));
  • 写回答

3条回答 默认 最新

  • duanliu8998 2016-05-14 05:26
    关注

    Your "best" datastring depends on your needs in the server side part. As an example, this jquery-ajax call send a object to a server side action (PHP) :

    var mydata = null;
    
    mydata = "hellostring=1";
    mydata = { title: "some" , value: "thing" };
    mydata = [1,2,3];
    
    $.ajax({
       cache: false, type: 'post', async: true, 
       data: mydata,
       url: 'some-script.php',
       success: function(resp){
           console.log("OK",resp);
       },
       error: function(e){
           console.log(e.responseText);
       }
    });
    

    As result, in your serve side you may have this script, which will return the same as you send:

    // some-script.php
    <?php 
        echo print_r($_POST,true);
    ?>
    

    The outputs, for each kind of data (see the mydata variable) is:

    Case: mydata = "hellostring=1";

        Array( [hellostring] => "1" )    
    

    this mean, in serverside, you can:

     $_123 = $_POST["hellostring"];  
    

    Case mydata = { title: "some" , value: "thing" };

    As result, you get:

    Array
    (
        [title] => some
        [value] => thing
    )
    

    So you can:

    $title = $_POST['title'];  $value = $_POST['value'];
    

    Case mydata = [1,2,3];

    Surprise, this doesnt work, :) , you should wrap it, in this form:

    mydata = { some : [1,2,3] }

    So, you can proceed in your server-side the same as the previous case.

    Note:

    To avoid get hacked: (PHP CASE example) filter your input using:
    http://php.net/manual/es/function.filter-input.php

    More

    In order to have a more advanced data handling in your server side part, (that is: in the script who receive the ajax request) , you can make usage of json, in this way:

    Let start by supposing you are sending a object via javascript:

    // in your client part, 
       mydata = { title: "some" , value: "thing", mydog: "sammy" };
       ..do your ajax call stuff here..
    

    And, in your server side:

       <?php
           // some-script.php
           $obj = json_decode(file_get_contents('php://input'));
           echo $obj->title;  // output: "some"
           echo $obj->value;  // output: "thing"
           echo $obj->mydog;  // output: "sammy"
       ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止