2012-11-10 59 views
0

我有一个页面,用户填写$ _GET数据的某些选项。我想通过AJAX将这些$ _GET变量传递给.php脚本。但我的问题是,我如何传递他们迄今填写的$ _GET变量,而不刷新页面?

这是我的代码到目前为止。

$.ajax({ 
type: "GET", 
url: "serverside script to process on data", 
data:{name:youwant}, // Here is where I want to take what the user has filled out so 
        // far, and place it here all without refreshing the page 
success: function(data){ 
    alert("return here if success") 

} 
}) 
+0

为什么不能在JS提取'input'元素的值? –

+0

可能重复[获取值GET或POST变量使用JavaScript?](http://stackoverflow.com/questions/1961069/getting-value-get-or-post-variable-using-javascript) – h2ooooooo

回答

1

首先要发送,删除该任务分成若干小的:

1)获取/过程变量在JavaScript中

2)将它们发送到PHP

3)解析/处理取决于结果那些

4)发送响应返回的JavaScript

5)处理该响应,并显示一条消息给用户

在这个例子中看看, 我们假设加载了jquery.js。 假设我们要发送我们拥有的输入值 - 电子邮件和密码。

<script type="text/javascript"> 

    $("#Send").click(function(){ 

    $.ajax({ 

     type : "GET", 
     //Look carefully: 
     data : { 
      // it'll be PHP vars  // This is JS vars 
      email    : $("#email").val(), 
      password    : $("#password").val() 
     }, 

     success : function(respondFromPHP){ 

       alert(respondFromPHP); 
     } 
     }); 


    }); 

</script> 

<input type="text" id="email" /> 
<input type="password" id="password" /> 

<br /> 
<button id="Send">Send to php</button> 

在你的PHP脚本,只需处理你瓦尔,就像这样:

<?php 

print_r($_GET); // will print smth like Array("email" => "foo", "password" => "bar") 

// Then create function so that you can simplify handling of the vars. 
// Like this: 
function validate_password($password){} 
function validate_email($email){} 
+0

完美!谢谢一堆! –

1

我不知道你的代码,但你可以有一个形式,而是提交的,你把的onsubmit方法JavaScript函数。在这个函数中,你收集所有的变量并通过ajax传递它。

例子:<form name="form1" method="get" onSubmit="return send()">

<script> 
function send() { 
$.ajax(...); 

return false; 

} 
</script> 

您可以使用seralize function$就数据