首页 \ 问答 \ 在jQuery错误中解析JSON(Parse JSON in jQuery error)

在jQuery错误中解析JSON(Parse JSON in jQuery error)

这是从之前的一个问题开始的,但是已经重新聚焦以解决特定的jQuery问题。

我目前正在尝试将PHP / MySQL搜索中的JSON结果解析为一个简单的HTML表。 但是,使用搜索时,我的表中没有数据返回。 我从Ajax请求得到响应,因为当我在Firebug中调试我的搜索页面时,我的请求以这个正确的JSON字符串返回:

[{"ARTIST":"Coldplay","TRACKTITLE":"Fix You","PLAYLIST":"Rock"},{"ARTIST":"Katy Perry","TRACKTITLE":"Roar","PLAYLIST":"Pop"}]

在我的jQuery文件中,我可以解析JSON以将每个{}数据字符串附加到HTML表的一行中(将ARTIST,TRACKTITLE和PLAYLIST作为我的列标题)。 我不清楚我出错的地方以及为什么我的JSON字符串没有正确转换为我的HTML表格,所以任何以正确的方式解析这些数据的指针都会有所帮助。

jQuery文件

$.post('ajax/name.php', {name: name}, function(data) {

var sentData=JSON.parse(data)

for(var i = 0; i < sentData.ARTIST.length; ++i)
var tr = $('<tr/>');
tr.append("<td>" + sentData.ARTIST + "</td>");
tr.append("<td>" + sentData.TRACKTITLE + "</td>");
tr.append("<td>" + sentData.PLAYLIST + "</td>");
$('#multiple').append(tr);
});

HTML提取

<table class="table hovered" id="multiple">
  <thead>
        <tr>
          <th class="text-left">Artist</th>
          <th class="text-left">Track Title</th>
          <th class="text-left">Playlist</th>
        </tr>
  </thead>
 </table>

更新

我添加了header('Content-Type: application/json'); 进入我的PHP文件,现在Firebug显示一个JSON选项卡,这是个好消息。 但是我仍然无法将JSON解析为HTML表格。


This follows on from a previous question of mine but has been refocused to address a specific jQuery issue.

I am currently trying to parse JSON results from a PHP / MySQL search into a simple HTML table. However, no data is returned into my table when using the search. I am getting a response from the Ajax request as when I debug my search page in Firebug my request is returned in this correct JSON string:

[{"ARTIST":"Coldplay","TRACKTITLE":"Fix You","PLAYLIST":"Rock"},{"ARTIST":"Katy Perry","TRACKTITLE":"Roar","PLAYLIST":"Pop"}]

Where in my jQuery file can I parse the JSON to append each string of {} data into a row of an HTML table (with ARTIST, TRACKTITLE and PLAYLIST as my column headers). I'm unclear as to where i'm going wrong and why my JSON string is not being converted into my HTML table correctly, so any pointers in the correct way to parse this data would be helpful.

jQuery file

$.post('ajax/name.php', {name: name}, function(data) {

var sentData=JSON.parse(data)

for(var i = 0; i < sentData.ARTIST.length; ++i)
var tr = $('<tr/>');
tr.append("<td>" + sentData.ARTIST + "</td>");
tr.append("<td>" + sentData.TRACKTITLE + "</td>");
tr.append("<td>" + sentData.PLAYLIST + "</td>");
$('#multiple').append(tr);
});

HTML extract

<table class="table hovered" id="multiple">
  <thead>
        <tr>
          <th class="text-left">Artist</th>
          <th class="text-left">Track Title</th>
          <th class="text-left">Playlist</th>
        </tr>
  </thead>
 </table>

Update

I added header('Content-Type: application/json'); into my PHP file and now Firebug is displaying a JSON tab, which is good news. However I still can't parse that JSON into the HTML table..


原文:https://stackoverflow.com/questions/20762405
更新时间:2023-11-09 19:11

最满意答案

如果我理解正确,那么尝试这样的事情:

在控制器中:

def search
  @user = User.find_by_user_no(params[:user_no])
end

在形式上:

<%= form_for :user ,:url => {:action => "search" }, remote: true do |f| %>
    <div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
       <%= f.text_field :user_no,:class => "form-control",placeholder:"user number" %>
    </div>
<% end %>

remote: true表示请求将是异步的。

在表中查看:

<div id="search-output-table">
   <%= render partial: "search_output_table", locales: {user: @user} %>
</div>

app/views/users/_search.js.erb

$("#search-output-table").html("<%= escape_javascript( render(partial: "search_output_table") ) %>");

app/views/users/_search_output_table.html.erb

<table>
  <tr>
    <th>User Name</th>
    <th>User Email</th>
    <th>User Number</th>
  </tr>
  <tr>
    <td><%= user.name %></td>
    <td><%= user.email %></td>
    <td><%= user.number %></td>
  </tr>
</table>

If I understand you correctly then try something like that:

In controller:

def search
  @user = User.find_by_user_no(params[:user_no])
end

In view with form:

<%= form_for :user ,:url => {:action => "search" }, remote: true do |f| %>
    <div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
       <%= f.text_field :user_no,:class => "form-control",placeholder:"user number" %>
    </div>
<% end %>

remote: true means that request will be asynchronous.

In view with table:

<div id="search-output-table">
   <%= render partial: "search_output_table", locales: {user: @user} %>
</div>

In app/views/users/_search.js.erb:

$("#search-output-table").html("<%= escape_javascript( render(partial: "search_output_table") ) %>");

In app/views/users/_search_output_table.html.erb:

<table>
  <tr>
    <th>User Name</th>
    <th>User Email</th>
    <th>User Number</th>
  </tr>
  <tr>
    <td><%= user.name %></td>
    <td><%= user.email %></td>
    <td><%= user.number %></td>
  </tr>
</table>

相关问答

更多
  • 无法读取work_here.js.erb,因为您从未调用它。 总是重定向。 请求为js格式时呈现它。 def work_here @company = Company.find(params[:id]) current_user.work_apply(current_user, @company) respond_to do |format| format.html { redirect_to company_path } format.js { render } end end Th ...
  • 如果我理解正确,那么尝试这样的事情: 在控制器中: def search @user = User.find_by_user_no(params[:user_no]) end 在形式上: <%= form_for :user ,:url => {:action => "search" }, remote: true do |f| %>
    您可以不提供任何内容: render :nothing => true 请参阅: http : //guides.rubyonrails.org/layouts_and_rendering.html#using-render You can render nothing with: render :nothing => true See: http://guides.rubyonrails.org/layouts_and_rendering.html#using-render
  • 我认为rails在更新之前需要url参数。 尝试像这样切换订单: <%= link_to_remote "<", :url=>{:action=>'ajax_calendar',:month => (@date.beginning_of_month-1).strftime("%Y-%m")}, :update=>'calendar' %> 但是,这可能不是它。 你的link_to_remote看起来不错,它可能是控制器里的东西。 你能告诉我们你的控制器代码吗? I was getting this err ...
  • 不知道为什么你需要宝石,但这里是搜索宝石的好地方: https : //www.ruby-toolbox.com/尝试自己实现ajax搜索。 在Rails中很容易=) Not sure why you need gem for this, but here is good place to search gems: https://www.ruby-toolbox.com/ Try to implement ajax search by yourself. It's easy in Rails =)
  • 可能是ajax调用中的问题, 在application.js中 $('div.wyszukiwarka form input.btn').submit(function() { $.get($this.action, $(this).serialize(), null, "script"); // what is $this? $(this) is button instead of form return false; }); 尝试这个 $('div.wyszukiwarka fo ...
  • 你可能正在重复调用绑定事件。 (添加控制台日志以进行检查) 没有必要绑定ajax:success事件。 (试着理解为什么你甚至插入它,因为你不需要)。 您的远程.js将转到“create.js.erb代码”,因此请尝试删除绑定事件,并单独使用$()。prepend代码行。 you're probably getting duplicate calls to the binded event. (add a console log to check) There's no need to bind an aj ...
  • ajax的意思是在没有任何页面刷新的情况下进行操作,以便使用ajax来更改视图,您需要将控制器呈现的所有html传递回作为对ajax调用的响应然后使用javascript替换当前页面的内容使用html从ajax响应中获取。 The point of ajax is to do stuff without any page refresh so to use ajax to change the view you would need to pass all the html rendered by the ...
  • 阅读此jquery-ujs问题: 事件ajax:表单替换后不会触发完成 Read this jquery-ujs issue: Event ajax:complete does not get triggered after form-replacement

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。