简体   繁体   English

使用JavaScript从php文件渲染JSON数据

[英]Render JSON data from php file using javascript

I'm producing a web app that lists all tweets based on a city that a user enters into a HTML form. 我正在制作一个Web应用程序,该应用程序根据用户输入HTML表单的城市列出所有推文。 It produces a $_SESSION['city'] variable from the form's post data. 它从表单的发布数据中生成$_SESSION['city']变量。

Then the php file uses the session variable as a parameter for my query. 然后,php文件将会话变量用作我的查询的参数。 This is fine and when I navigate to tweets.php the JSON is successfully pulled from twitter after I submit the form. 很好,当我导航到tweets.php时,在提交表单后,JSON已成功从twitter提取。

There are two fields I'd like to render from my JSON file name and text . 我想通过JSON文件nametext呈现两个字段。 I've tried using the javascript below but to no avail. 我尝试使用下面的JavaScript,但无济于事。 Can anyone tell me where I'm going wrong? 谁能告诉我我要去哪里错了?

$(document).ready(function() {

$.getJSON("http://localhost/Labs/AppName/public/js/tweets.php", function(feeds) {
    var feedHTML = "";
    for(var i=0; i<feeds.length; i++) {
        var tweetname = feeds[i].user.name;
        var tweet = feeds[i].text;

        feedHTML += "<p>" + tweetname + "<br />" + tweet + "</p>"; //RENDER JSON VARS
    }

    $("#twitter-feed h3").after(feedHTML);
});

});

A quick summary of the algorithm: 该算法的简要概述:

  1. User enters "London" into web form on index.php (form posts to same page). 用户在index.php上的Web表单中输入“伦敦”(表单发布到同一页面)。
  2. $_POST variable assigned to $_SESSION variable $_POST变量分配给$_SESSION变量
  3. Session variable used as parameter in "https://api.twitter.com/1.1/search/tweets.json?q=".$city); "https://api.twitter.com/1.1/search/tweets.json?q=".$city);用作参数的会话变量"https://api.twitter.com/1.1/search/tweets.json?q=".$city);
  4. Javascript appends the HTML in <div id="twitter-feed"> </div> with the tweets. Javascript在HTML的<div id="twitter-feed"> </div>附加推文。

Sample JSON output (reduced): 样本JSON输出(精简):

         "created_at":"Wed Feb 04 14:27:27 +0000 2015",
     "id":562980760127557633,
     "id_str":"562980760127557633",
     "text":"http:\/\/t.co\/lbqnmNrHue",
     "source":"IFTTT<\/a>",
     "truncated":false,
     "in_reply_to_status_id":null,
     "in_reply_to_status_id_str":null,
     "in_reply_to_user_id":null,
     "in_reply_to_user_id_str":null,
     "in_reply_to_screen_name":null,
     "user":{
        "id":23638744,
        "id_str":"23638744",
        "name":"adrian bonnington",
        "screen_name":"xymalf",
        "location":"UK",
        "profile_location":null,
        "description":"unemployed electronics engineer.",
        "url":"http:\/\/t.co\/XmSePpitdx",
        "entities":{
           "url":{
              "urls":[
                 {
                    "url":"http:\/\/t.co\/XmSePpitdx",
                    "expanded_url":"http:\/\/about.me\/xymalf",
                    "display_url":"about.me\/xymalf",
                    "indices":[
                       0,
                       22
                    ]
                 }
              ]
           },
           "description":{
              "urls":[

              ]
           }
        },

ajax function like that can make same changes u want 像这样的ajax函数可以进行您想要的相同更改

$.ajax({ $ .ajax({

        url: '/Labs/AppName/public/js/tweets.php',

        type: 'post',
        data:{'city':city},
        dataType: 'json',
        timeout: 20000,
        tryCount: 0,
        retryLimit: 3,
        success: function(feeds) {
            $.each(feeds.length, function(k, each_user) {

                 feedHTML += "<p>" + each_user.name + "<br />" + each_user.text + "</p>";

            });
            $("#twitter-feed h3").after(feedHTML);
        }
    })

JSON as response value from ajax in most cases needs to be converted to JavaScript object. 在大多数情况下,作为来自ajax的响应值的JSON需要转换为JavaScript对象。 After that everything is really simple. 之后,一切真的很简单。 Just iterate over array of objects, and use them as you wont. 只是遍历对象数组,并按需使用它们。 Down belove code work if response is a string otherwise check JSON validation http://jsonlint.com/ 如果响应是字符串,请执行belove代码,否则请检查JSON验证http://jsonlint.com/

$(document).ready(function() {
     $.getJSON("http://localhost/Labs/AppName/public/js/tweets.php", function(feeds) {
       var feed = JSON.parse(feeds); //Java script object        
       var feedHTML = "";
       for(var i=0; i<feeds.length; i++) {    
         feedHTML += "<p>" + feeds[i].user.name + "<br />" + feeds[i].text + "</p>"; 
       }
       $("#twitter-feed h3").after(feedHTML);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM