2015-04-23 72 views
0

使用JQuery,我可以使用下面的代碼通過ajax發送1個參數,並返回請求的數據。JQUERY AJAX PHP MYSQLi傳遞多個參數

我的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 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執行並獲取PORT,並通過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上。

所以我的問題是:如何在不刷新頁面的情況下傳遞一個或多個參數?

請原諒我的無知......我想在Jquery和Ajax上變得更好。

請幫忙。

+0

請進入[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)幫助您解決問題的習慣。 –

回答

2

你剛纔添加到陣列 -

$('#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){ 
+0

這麼簡單,但是如果他們離開,說PORT空白並進入VOYAGE會發生什麼?這會拋棄一切嗎? –

+1

不,PORT的值將作爲空白髮送。 –

+0

因此,對於表單中的每個可用變量,我都可以將它添加到jquery中?你告訴我這就是這麼簡單?哈哈....我會嘗試這個,並讓你知道我是否成功。謝謝您的幫助,好的先生。 –

1
$.post("api/summary.php", { name: "John", time: "2pm"} , function(data){ 
     $('#content').html(data); 
    }); 

像這樣的事情?只需附加額外的數據,用逗號分隔。

+0

與上面相同的問題:如果用戶輸入VOYAGE,但不輸入PORT,會發生什麼? –

+1

發送的值將爲空。 –

+0

因爲你的回答與Jay Blanchard的回答相同,所以給你一個滿意的答案,並且它是成功的。感謝您的評論。 –