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


how do i pass datastring parameter for jquery's .ajax() function properly?

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>');
        }
    });

使用上面的代码,我的用户名变量没有正确传递,我假设我对 datastring 参数进行编码的方式有问题,但我不确定如何正确执行此操作。

下面是我在登录时使用的 php 代码.php要将用户名插入数据库,每个新条目都不会输入用户名字段。

$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));

您的"最佳"数据字符串取决于您在服务器端部分的需求。例如,这个jquery-ajax调用将对象发送到服务器端操作(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);
   }
});

因此,在您的服务端,您可能有此脚本,它将返回与您发送的相同内容:

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

每种数据(参见 mydata 变量(的输出为:

大小写:mydata = "hellostring=1";

    Array( [hellostring] => "1" )    

这意味着,在服务器端,您可以:

 $_123 = $_POST["hellostring"];  

案例 mydata = { 标题: "一些" , 值: "事物" };

结果,您可以获得:

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

因此,您可以:

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

案例 mydata = [1,2,3];

令人惊讶的是,这不起作用,:),您应该以以下形式包装它:

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

因此,您可以在服务器端继续与前一种情况相同的操作。

注意:

为避免被黑客入侵:(PHP CASE示例(使用以下方法过滤您的输入:
http://php.net/manual/es/function.filter-input.php

更多

为了在服务器端部分(即:在接收 ajax 请求的脚本中(进行更高级的数据处理,您可以通过以下方式使用 json:

让我们首先假设您通过javascript发送一个对象:

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

而且,在服务器端:

   <?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"
   ?>

尝试将其作为常规JavaScript对象传递

var dataObj = {'username': username};
$.ajax({
    type: "POST",
    url: "signinout.php",
    data: dataObj,

尝试改用data: "username="+username,

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