动态填写与jQuery表单值 [英] Dynamically fill in form values with jQuery

查看:109
本文介绍了动态填写与jQuery表单值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何与纯PHP这样做,但我必须这样做无需重新加载页面。有反正用jQuery有效地拉回来一些数据库的结果(根据什么用户输入窗体上的第一个文本字段),然后填充一些数据,其余字段拉回从数据库查询?

I know how to do this with pure PHP but I need to do this without reloading the page. Is there anyway with jQuery to effectively pull back some database results (based on what a user has input in the first text field on a form) then populate some of the remaining fields with data pulled back from a db query?

从本质上讲,我想看到​​用户远离文本字段(通过tab键切换出或点击下一个字段)和热潮,查询使用该字段中输入的值提交和随后的字段,然后填充瓦特/ OA页面重载。

Essentially I would like to see the user move away from the text field (either by tabbing out or by click in the next field) and boom, the query is submitted using the value entered in that field and the subsequent fields are then populated w/o a page reload.

我熟悉的jQuery的基础知识,但我没有用它做这样在我拉回来的数据从服务器,并试图填充它的客户端什么。

I am familiar with the basics of jQuery but I haven't used it to do anything like this in which I am pulling data back from the server and trying to populate it client side.

任何建议/就如何最好地开始使用,这将是非常美联社preciated例子。谢谢你。

Any suggestions / examples on how to best get started with this would be very much appreciated. Thanks.

  • 尼古拉斯

推荐答案

假设这个例子中的HTML:

Assuming this example HTML:

<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />

您可以有此javascript:

You could have this javascript:

$("#email").bind("change", function(e){
  $.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
        function(data){
          $.each(data, function(i,item){
            if (item.field == "first_name") {
              $("#first_name").val(item.value);
            } else if (item.field == "last_name") {
              $("#last_name").val(item.value);
            }
          });
        });
});

然后,只需你有一个PHP脚本(在这种情况下lookup.php),它的电子邮件中的查询字符串,并返回一个JSON格式数组回来,你要访问的值。这是实际访问数据库,以查找值的部分:

Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:

<?php
//look up the record based on email and get the firstname and lastname
...

//build the JSON array for return
$json = array(array('field' => 'first_name', 
                    'value' => $firstName), 
              array('field' => 'last_name', 
                    'value' => $last_name));
echo json_encode($json );
?>

您会希望像消毒邮件输入等做其他事情,而应该让你在正确的方向前进。

You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.

这篇关于动态填写与jQuery表单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆