2017-05-24 44 views
1

我想通過post請求將數組和其他變量從jQuery代碼傳遞到php,但我不知道如何在同一時間傳遞數組和變量。同時將數組和變量從jquery傳遞到php

我試過這段代碼:

var new_location_name = ""; 
var new_location_id = ""; 
var old_location_name = []; 
var selected_name = []; 
var selected_id = []; 
var user = '<?php echo $current_user ;?>'; 

    $(document).ready(
      $("#transfer").click(function(){ 
       $.ajax({ 
        type: "POST", 
        url: "update.php", 
        data: "username="+user+"&new_location_name="+new_location_name+"&new_location_id"+new_location_id+"&"+{ old_location_name : old_location_name }+"&"+{ selected_name : selected_name }+"&"+{ selected_id : selected_id }, 
       }); 
       return false; 
      }); 
    }); 

回答

0

您可以將多個參數作爲數組或字符串相同。數據的左側是API所期望的值作爲參數名稱。

var new_location_name = ""; 
var new_location_id = ""; 
var old_location_name = []; 
var selected_name = []; 
var selected_id = []; 
var user = '<?php echo $current_user ;?>'; 

    $(document).ready(
      $("#transfer").click(function(){ 
       $.ajax({ 
        type: "POST", 
        url: "update.php", 
        data: {username: user, 
          new_location_name: new_location_name, 
          old_location_name: old_location_name 
         } 
       }); 
       return false; 
      }); 
    }); 

你可以閱讀更多在這個問題:Pass Multiple Parameters to jQuery ajax call

+0

感謝您的快速響應,如果我發送這樣的數組和變量,我需要在php文件的另一邊做什麼來獲取每個數組和每個變量的值? –

+0

它們只是php函數的參數,然後您可以將它們作爲JSON訪問。 – Avitus

2

創建一個對象,序列化和發送:

var obj = { 
    key1: 'value1', 
    key2: ['one','two','three'], 
    key3: { 
     key3_0: 'value3_0' 
    } 
} 
var jsonData = JSON.stringify(obj); 

$.ajax({ 
    method: "POST", 
    url: "update.php", 
    data: jsonData 
}); 
0

試試這個片斷

var array = []; 
$.ajax({ url: 'update.php', 
    data: {'array' : array}, 
    type: 'post', 
    dataType:'json', 
    success: function(output) { 
     alert(output); 
    }, 
    error: function(request, status, error) { 
     alert("Error"); 
    } 
}); 
-1

第一次檢查文件,該腳本必須在PHP文件,而不是.js文件;

1

JQuery的數據:

data: 
    { 
     username: user, 
     new_location_name: new_location_name, 
     new_location_id: new_location_id, 
     old_location_name: old_location_name, 
     selected_name : selected_name, 
     selected_id : selected_id 
    } 

在你的PHP腳本

<? $oldLocationName = $_REQUEST['old_location_name']; ?> 

等。