0

我按照教程来调整代码。在这里,我尝试在提供“ID”值时使用 AJAX 自动填充表单字段。我是 Jquery 的新手,无法使用此代码。

编辑 1:在测试代码时,Jquery 不会阻止表单提交和发送 AJAX 请求。

HTML 表单

<form id="form-ajax" action="form-ajax.php">
    <label>ID:</label><input type="text" name="ID" /><br />
    <label>Name:</label><input type="text" name="Name" /><br />
    <label>Address:</label><input type="text" name="Address" /><br />
    <label>Phone:</label><input type="text" name="Phone" /><br />
    <label>Email:</label><input type="email" name="Email" /><br />
    <input type="submit" value="fill from db" />
</form>

我尝试更改 Jquery 代码,但仍然无法正常工作。我认为 Jquery 在这里制造了一个问题。但我找不到错误或错误代码。如果您让我朝着正确的方向前进,那将非常有帮助。

编辑2:我尝试使用

return false; 

代替

event.preventDefault(); 

以防止表单提交,但它仍然无法正常工作。知道我在这里做错了什么吗?

jQuery

jQuery(function($) {

// hook the submit action on the form
$("#form-ajax").submit(function(event) {
    // stop the form submitting
    event.preventDefault();

    // grab the ID and send AJAX request if not (empty / only whitespace)
    var IDval = this.elements.ID.value;
    if (/\S/.test(IDval)) {

        // using the ajax() method directly
        $.ajax({
            type : "GET",
            url : ajax.php,
            cache : false,
            dataType : "json",
            data : { ID : IDval },
            success : process_response,
            error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
        });


    }
    else {
        alert("No ID supplied");
    }
};


function process_response(response) {
    var frm = $("#form-ajax");
    var i;

    console.dir(response);      // for debug

    for (i in response) {
        frm.find('[name="' + i + '"]').val(response[i]);
    }
}

});

ajax.php

if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
    // tell the browser what's coming
    header('Content-type: application/json');

    // open database connection
    $db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');

    // use prepared statements!
    $query = $db->prepare('select * from form_ajax where ID = ?');
    $query->execute(array($_GET['ID']));
    $row = $query->fetch(PDO::FETCH_OBJ);

    // send the data encoded as JSON
    echo json_encode($row);
    exit;
 }
}
4

2 回答 2

0

Replace the submit input with button:

<button type="button" id="submit">

Note the type="button". It's mandatory to prevent form submition

Javascript:

$(document).ready(function() {
    $("#submit").on("click", function(e) {
          $.ajax({type:"get",
                  url: "ajax.php",
                  data: $("#form-ajax").serialize(),
                  dataType: "json",
                  success: process_response,
                  error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
           });
    });
}); 
于 2014-09-21T09:16:39.767 回答
0

我看不到您将 json 响应解析为 javascript 对象(哈希)的位置。这个jQuery 方法应该会有所帮助。看起来您不是使用 jquery 发布表单,而是尝试发出获取请求。要使用 jquery 正确提交表单,请使用以下内容:

$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );

另外,您是否尝试过向表单元素添加 id 属性?

<input type="text" id="name" name="name"/>

以后更容易与他们联系

var element = $('#'+element_id);

如果这不是解决方案,您可以发布从您的请求返回的 json 吗?

于 2014-09-21T07:02:53.133 回答