jQuery 通过 AJAX 传递多个参数

jQuery passing multiple parameters via AJAX

使用 jQuery,我可以使用下面的代码通过 ajax 发送 1 个参数,并 return 请求的数据。

我的 javascript 文件名为:globals.js

 $('#submitButton').on('click', function(){
   var port = $('#port').val();  // single parameter passed from index.php
   if($.trim(port) != '')
   {
     $.post('api/summary.php', {port: port}, function(data){
       $('#content').html(data);
     });
   }
 });

以下是位于名为 index.php

的文件中的几个 INPUT 字段
 <input type="text" id="port" name="port" />
 <input type="text" id="voyage" name="voyage" />
 <input type="text" id="rep" name="rep" />
 // quite a few more input fields and select options as well

 <button type="submit" id="submitButton" name="submitButton">Submit</button>

 <script src="js/globals.js" type="text/javascript"></script>   // included javascript file above

因此,当用户输入端口并单击提交时,上面的 jQuery 会执行并获取端口,然后通过 ajax 调用,向其发送调用的 PHP 脚本:summary.php

 <?php
   include("../include/database.php");

   $_SESSION['where'] = "";
   $port = $_POST['port'];
   $voyage = $_POST['voyage'];
   $rep = $_POST['rep'];
   // more variables follow;

   // at this point, I can echo port and return in to the page, 
      or use it in a query, and return the data in a table if necessary

   echo $port;  // passed from jquery
   echo $voyage; // cannot pass from jquery
   echo $rep;  // cannot pass from jquery
   // and so on....

   ?>

我可以在上面jQuery指示的$('#content').html(data)中显示内容(现在只有PORT)

但我需要做的是让 jQuery 接受多个参数并将它们传递给我的 PHP 脚本。这就是我卡住的地方。

我知道问题出在我上面的jQuery。

所以我的问题是:如何在不刷新页面的情况下传递 1 个或多个参数?

你只需添加到数组 -

$('#submitButton').on('click', function(){
    var port = $('#port').val();  // single parameter passed from index.php
    var voyage = $('#voyage').val();
    // add other values here
    if($.trim(port) != '')
    {
        $.post('api/summary.php', {port: port, voyage: voyage /* add other values separated by commas */}, function(data){
$.post( "api/summary.php", { name: "John", time: "2pm"} , function(data){
       $('#content').html(data);
     });

是这样的吗?只需附上额外的数据,以逗号分隔。