2015-04-23 74 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的回答相同,所以给你一个满意的答案,并且它是成功的。感谢您的评论。 –