dongzuo9096 2016-07-16 03:48
浏览 36

将值从JQUERY传递给PHP,并返回JSON

When call php from jquery via ajax ,have any response .I changed the dataTypeand put jsoninstead html.I´m thinking the issue is that,for the ajax call never trigger the php code,it seems $_POST['retriveForm'] never carries a value.

PHP:

if(isset($_POST["retriveForm"])) {
    $data_json =array();
    $id  = $_POST['retriveForm'];
    $sql = "SELECT * FROM mytable WHERE Id = $id";
    while ($row = mysqli_fetch_array($db->consulta($sql)) {
            $data_json  = array('item1' => $row['item1'],'item2' => $row['item2']) ;
    }
    $data_json['item_array'] = call_a_function_return_array();//this works
    echo json_encode($data_json);
}

and jQuery :

$(document.body).on('click', '.edit', function() {
    var id = $(this).data('id');
    $.ajax({
        type: "POST",
        url: "is_the_same_page.php",
        data: {
            retriveForm: id
        },
        dataType: "json",
        success: function(response) {
            $('#myForm').find('input').eq(1).val(response.item1);
        }
    });
});

Code is all in the same page if that may be important.

  • 写回答

1条回答 默认 最新

  • dongpin3794 2016-07-16 04:14
    关注

    Since the AJAX code is in the same script, make sure you don't output any of the normal HTML in this case. Your PHP code should be at the very beginning of the script, before any HTML is output. And you should exit the script after echoing the JSON. Otherwise your JSON will be mixed together with HTML, and jQuery won't be able to parse the response.

    Also, you're not correctly adding to $data_json in your loop. You're overwriting the variable each time instead of pushing onto it.

    <?php
    // code here to set up database connection
    if(isset($_POST["retriveForm"])) {
        $data_json =array();
        $id  = $_POST['retriveForm'];
        $sql = "SELECT * FROM mytable WHERE Id = $id";
        while ($row = mysqli_fetch_array($db->consulta($sql)) {
            $data_json[]  = array('item1' => $row['item1'],'item2' => $row['item2']) ;
        }
        $data_json['item_array'] = call_a_function_return_array();//this works
        echo json_encode($data_json);
        exit();
    }
    ?>
    <html>
    <head>
    ...
    

    Then in the success function, you'll need to index the elements of response, since it's an array, not a single object.

    评论

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上