【问题标题】:How to display json data from js file in html page inside div如何在div内的html页面中显示来自js文件的json数据
【发布时间】:2017-02-06 05:04:16
【问题描述】:

在这里,我正在从 db 中以 JSON 格式获取数据到我的 .js 文件中,我也正在进入 div 中。但我没有在我的 HTML 页面中获取 div。请谁能告诉我如何在我的 HTML 中显示page.Below 是我的代码:

我的 json 数组:

[{"chat_question_id":"1",
 "chat_question_title":"What is PHP?"},
 {"chat_question_id":"17",
 "chat_question_title":"what is php?",}

下面是我的js代码:

    function ChatQuestionsInfo(bRowId)
    {
    var actionType = "";
    var hdnFlagForSearchQue = $("#hdnFlagForSearchQue").val();
    if(hdnFlagForSearchQue=="insert"){
        actionType = "ChatQuestionsInfo";
    } else {
        actionType = "searchQuestiontitle";
    }
    if($.trim($("#questionname").val())==""){
        $("#questionname").focus();
        alert("Enter Question Name");
        return false;
    }
    if($.trim($("#technologytags").val())==""){
        $("#technologytags").focus();
        return false;
    }
    $.post(rootUrl+"includes/ajax/ajax_chat.php", {action: actionType,bRowId:bRowId,bQuestionName: $.trim($("#questionname").val()),bTechnologyTags: $.trim($("#technologytags").val())},
    function(data){
       var htmlText = '';
  for ( var key in data ) {
            htmlText += '<div class="tab-content">';
            htmlText += '<div id="newquestions"> : ' + data[key].chat_question_title + '</div>';
            htmlText += '</div>';
        }
        $('.chat_body_form').append(htmlText);
    }, "json");
    return false;
    }

HTML 代码:

<div id="newquestions"></div>

【问题讨论】:

  • 警报有效???
  • 不,它不工作
  • 在控制台中打印您的对象,然后向我展示console.log(chat) ;,它将在控制台窗口中打印
  • row.date 的值是多少?给我们显示行或聊天变量的数据。
  • 我更改了我的代码 我收到这样的警报 我收到这样的警报:
    :什么是 PHP?

标签: javascript php jquery html json


【解决方案1】:

我认为您需要进行 2 处更改,其中 1 处位于 ajax_chat.php 文件中。第二个在你的 javascript 中。

  1. 每个 JSON 输出都需要有纯 JSON 输出,以便 javascript(或 jquery)可以轻松读取它。所以在 ajax_chat.php 文件的输出中,你必须设置一个标题来提供正确的输出内容类型。

例如

header('Content-Type:application/json');
echo json_encode('your varialbe array');
  1. 在 jquery 中最好使用 $.each 然后 for 循环,也可以直接在循环中追加数据。

例如

function(data){
$.each(data,function(i){
    $('.chat_body_form').append('<div class="tab-content"><div id="newquestions"> : '+ $(this).chat_question_title + '</div></div>';
 });    
}

我认为这些更改会起作用,而且代码非常简单干净,易于理解或更改,

谢谢...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2020-12-13
    • 2019-10-31
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多