Ajax 调用以从 php 返回的对象填充表单字段


Ajax call to populate form fields from php returned object

首先,我使用$.getJSON()通过GET请求发送用户ID。

Javascrit部分:

        $.getJSON("this_file.php?id=1", null, function(data){
            $('input#id').val(data.id);
            $('input#username').val(data.username);
            $('input#first_name').val(data.first_name);
        });

当通过 GET 请求显示用户 ID 时,我运行一个函数来向我返回一个包含用户详细信息的 OBJECT。

PHP 部分 (this_file.php):

    <?php
        $id =  $_GET['id'];
        $user = $db->find_by_id($id); //This function will return a single user details.
        echo json_encode($user);
     ,  //echo $user output is: {"id" : "1", "username" : "bobu", "first_name" : "bob"} 
     ?>

以下是要填充的表单字段。

网页表单:

<input type="text" value="" name="id" id="id">
<input type="text" value="" name="username" id="username">
<input type="text" value="" name="first_name" id="first_name">

在浏览器控制台中,来自 GET 请求的响应按预期返回:

{"id" : "1", "username" : "bobu", "first_name" : "bob"}

但是,这些值未显示在表单上,如何进行此方法?

我会使用javascript,但如果你不打算:

改变

<input type="text" value="" name="id" id="id">
<input type="text" value="" name="username" id="username">
<input type="text" value="" name="first_name" id="first_name">

自:

<input type="text" value="<?php if($sentVar==1){echo $id;} ?>" name="id" id="id">
<input type="text" value="<?php if($sentVar==1){echo $username;} ?>" name="username" id="username">
<input type="text" value="<?php if($sentVar==1){echo $first_name;} ?>" name="first_name" id="first_name">

然后在 PHP 触发时添加一个条件:

$sentVar=1;

或者只是尝试:

<input type="text" value="<?php echo $id; ?>" name="id" id="id">
<input type="text" value="<?php echo $username; ?>" name="username" id="username">
<input type="text" value="<?php echo $first_name; ?>" name="first_name" id="first_name">