weixin_33714884 2015-11-14 12:01 采纳率: 0%
浏览 3

无法访问哈希值

Code inside index.php:

<!DOCTYPE html>
<html lang="en-us" dir="ltr">
    <head>
        <meta charset="utf-8" />
        <script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $( ".trashitem" ).click(function(e) {
                    e.preventDefault();
                    var trashlink = $(this);
                    var res = confirm("Are you sure you want to trash the selected item?");
                    if ( res != false ) {
                        var trashurl = trashlink.attr("href");
                        var trashid = trashlink.data("id");
                        $.ajax({
                            url: trashurl,
                            type: "POST",
                            data: { "trashid": trashid },
                            datatype: "json",
                            success: function(response) {
                                console.log(response);  // Output: {"success":true,"error":false}
                                console.log(response.success);  // Output:   undefined
                                if (response.success == true) {
                                    trashlink.parents("li").fadeOut(300, function() {
                                        trashlink.parents("li").remove();
                                    });
                                }
                            }
                        });
                    }
                });
            });
        </script>
    </head>
    <body>
        <ul>
            <li><a class="trashitem text-color-alert" href="trash.php" data-id="20">Trash</a></li>
            <li>This is undeletable item.</li>
        </ul>
    </body>
</html>

Code inside trash.php is:

<?php
    $id = $_POST['trashid'];
  $error = false;
  $success = false;
  if ($id) {
    $success = trash_post($id);
    $response = array(
      'success' => $success,
      'error' => $error
    );
  }
  echo json_encode( $response );

  function trash_post( $target_id ) {
    return true;
  }

Please look at the first code snippet in index.php where:

console.log(response);  // Output: {"success":true,"error":false}

but when I want to access success:

console.log(response.success);  //   undefined

Why does it give me undefined instead of true? I have come across a few posts on Stackoverflow similar to mine, but they were not helpful for me.

  • 写回答

3条回答 默认 最新

  • weixin_33695450 2015-11-14 12:04
    关注

    Probably response is just a string but not a Object

    try

    var a = JSON.parse(response);
    console.log(a.success);
    

    or try adding this at the top of your php file

    header('Content-Type: application/json');
    

    this set's the content type of php file as JSON

    评论

报告相同问题?