从Ajax请求向PHP发布多个值

时间:2017-12-21 15:05:30

标签: javascript php jquery ajax

我有一个Ajax请求来保存JavaScript中的数据,并使用单独的(“saveData.php”)PHP文件将其写入文件。我想知道我是否可以在同一个Ajax请求中“POST”多个JavaScript变量/字符串。

例如,我目前有这个:

function saveData(){ //sends an AJAX request to saveData.php
$.ajax({
    type: "POST",
    url: "saveData.php",
    dataType: "text/plain",
    ContentType: "charset=utf-8",
    data: {"data": dataString},
  })
}

这可以通过我的PHP文件很好用,该代码如下:

$data = $_POST["data"];
$theFile = fopen("Data/" . FileNameHere . ".txt", "a+");

// Save data into a file based on their username
fwrite($theFile, $data);
fclose($theFile);   

但我想根据用户ID保存文件,这是一个JavaScript变量。

我可以这样做:

function saveData(){ //sends an AJAX request to saveData.php
$.ajax({
    type: "POST",
    url: "saveData.php",
    dataType: "text/plain",
    ContentType: "charset=utf-8",
    data: {"data": dataString},
    data1: {"data1": userID},   <-----new line with JS variable 'userID'
  })
}

这样的PHP文件:

// Prepare line of data to save.
$data = $_POST["data"];
$userID = $_POST["data1"];     <--------New code to POST "data1" from Ajax
$theFile = fopen("Data/" . $userID . ".txt", "a+");

// Save data into a file based on their username
fwrite($theFile, $data);
fclose($theFile);   

1 个答案:

答案 0 :(得分:6)

是的,您可以,您正在传递一个JSON对象,因此它可以拥有任意数量的属性。

详细了解如何在服务器端via ajax发送多个数据。 试试这个

function saveData(){ //sends an AJAX request to saveData.php
$.ajax({
    type: "POST",
    url: "saveData.php",
    dataType: "text/plain",
    ContentType: "charset=utf-8",
    data: {
            "data": dataString, 
            "data2":val2,
            "data3":val3,
            "data4":val4
          },
  })
}

这样的PHP文件:

$data = $_POST["data"];
$userID = $_POST["data2"];
$theFile = fopen("Data/" . $userID . ".txt", "a+");

// Save data into a file based on their username
fwrite($theFile, $data);
fclose($theFile);