dongma7725
2015-12-09 18:16
浏览 86

使用自定义MVC从JQuery ajax(),PHP和MySQL检索JSON数据

I have been searching everywhere and I am not getting anywhere. This is what I am using: Custom PHP MVC this is what I am trying to get: From userView.php I want to replace an id="ShowName" with JSON data from a ajax Call using JQuery

This is what I have: userController.php

if (isset($_POST['id'])) {
    $this->getView('users', $this->object->getUser($_POST['id']));
}

userModel.php

public function getUser($id) {
    $this->user = array();

    parent::getConnection();
    $this->sql = $this->dbh->query("SELECT * FROM User WHERE idUser='". $id ."'");
    parent::errorHandler();
    $this->results = $this->sql->fetch(PDO::FETCH_ASSOC);
    $this->user[] = array(
        'name' => $this->results['name'],
        'lastname' => $this->results['lastname'],
        'email' =>  $this->results['email']
        );
    $obj['user'] = $this->user;

    parent::closeConnection();
    header('Content-Type: application/json');
    print json_encode($obj);

}

userView.php

<select class="form-control blue select" id="getUserID">
    <option value="default">Seleccione un Usuario</option>
    <?php $this->object->getUserslist();?>
</select>

<span id="name"></span>

Method getUsersList() inside userModel

public function getUsersList() {

    parent::getConnection();
    $this->sql = $this->dbh->query("SELECT * FROM User ORDER BY name ASC");
    parent::errorHandler();
    while($this->results = $this->sql->fetch(PDO::FETCH_ASSOC)) {
        echo "<option value='" . $this->results['idUser'] . "'>" . $this->results['name'] . "</option>";
    }
    parent::closeConnection();

}

JQuery

$("#getUserID").change(function(){
    var userID = $("#getUserID").val();
    $.ajax({
        type: 'POST',
        url: 'user',
        data: 'id='+userID,
        dataType: 'json',
        success: function(data){
            var obj = $.parseJSON(data);
            alert(obj.name)
        }
    });
});

It retrieves JSON data at the very top of the html file, but the alert is not prompting, so I guess it gets data before the success is called.

Direct Question: How can I retrieve the JSON data from PHP so I can use it in html from JQUERY ajax Response?

Thanks!!!!

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douju2012 2015-12-09 18:44

    In userModel.php

    change

    $this->user[] = array(
        'name' => $this->results['name'],
        'lastname' => $this->results['lastname'],
        'email' =>  $this->results['email']
        );
    $obj['user'] = $this->user;
    

    to:

    $obj = array(
        'name' => $this->results['name'],
        'lastname' => $this->results['lastname'],
        'email' =>  $this->results['email']
        );
    

    See if the alert prompt returns what you expect.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题