1

codeigniterを使用してAJAX呼び出しメソッドを自分のWebサイトに実装しようとしています。これは、データベースからライブアップデートを取得できるようにAJAXを使用する理由です。

クリックボタンは機能し、すべてのJSONデータを表示しますが、問題は、特定の配列を表示しようとすると、それを認識せず、すべての文字を繰り返し処理しているように見えることです。

また、もう1つの奇妙なことは、アラートが呼び出されているときに、特定の配列、たとえば配列IDを出力できるようにしたいhtmlタグとheadタグを確認できることです。」

私がそれを試して解決するためにしたこと

  • データ型に警告し、それが文字列であることがわかりました

  • 私はajaxをcodeigniterではなく通常のPHPで動作させることができたので、データベースに問題はありません

  • また、jQuery.parseJSONを使用しようとしたので、強制的にjsonにすることができますが、スクリプトが実行されませんでした

  • 私はJSONlintを使用しましたが、その有効なJSON

どんな助けでもいただければ幸いです

Consolelog

<html>
    <head>

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAXpGbk1wkkaPiv_qkBevxAP9s4kk0oiiU&sensor=false"></script>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

[
[
    {
        "id": "1",
        "postcode": "NW6",
        "imgurl": "hello.jpeg",
        "from_user": "henny",
        "created_at": "2013-03-18 23:03:00"
    },
    {
        "id": "2",
        "postcode": "NW2",
        "imgurl": "test.jpeg",
        "from_user": "belly",
        "created_at": "2013-03-15 23:03:00"
    }
]
]

コントローラ

public function insertJSON()
{
    $this->load->model("values");
    $queryresults = $this->values->getDb();

    $arrays = array($queryresults);

    echo json_encode($arrays);  
}

意見

<script type='text/javascript' language='javascript'>

  $('#getdata').click(function (data) {

      $.ajax({

          url: '<?php echo base_url().'index.php/welcome/insertJSON';?>',
          type: 'POST',
          cache: 'false',
          datatype: 'json'

      }).done(function (data) {

         alert(data);

      });

  });

</script>

json_encode

[
[
    {
        "id": "1",
        "postcode": "NW6",
        "imgurl": "hello.jpeg",
        "from_user": "henny",
        "created_at": "2013-03-18 23:03:00"
    },
    {
        "id": "2",
        "postcode": "NW2",
        "imgurl": "test.jpeg",
        "from_user": "belly",
        "created_at": "2013-03-15 23:03:00"
    }
]
]
4

1 に答える 1

2

コントローラ関数から正しい応答ヘッダー(application / json)を送り返す必要があります。

コントローラを次のように変更してみてください。

public function insertJSON()
{
    $this->load->model("values");
    $queryresults = $this->values->getDb();

    $arrays = array($queryresults);

    $this->output->set_content_type('application/json')
                 ->set_output(json_encode($arrays));
}
于 2013-03-19T03:26:22.990 に答える