我不知道這段代碼有什麼問題。我想從網址獲取數據,並在用戶將該網址粘貼到文本框中時顯示它們。這裏是我的代碼:使用Ajax和Nokogiri從rails中提取URL中的數據
應用程序/資產/ JavaScript的:
$(document).ready(function() {
$("#post_content").bind('paste', function(e) {
var el = $(this);
setTimeout(function() {
var text = $(el).val();
// send url to service for parsing
$.ajax('/links/linkpreview', {
type: 'POST',
data: { url: text },
success: function(data,textStatus,jqXHR) {
// handle received data
$("#preview-title").text(data['title']);
},
error: function() { alert("error"); }
});
}, 100);
});
});
應用程序/控制器/ links_controller.rb:
def linkpreview
url = params[:url]
doc = Nokogiri::HTML(open(url), nil, 'UTF-8')
title = ""
description = ""
url = ""
image_url = ""
doc.xpath("//head//meta").each do |meta|
if meta['property'] == 'og:title'
title = meta['content']
elsif meta['property'] == 'og:description' || meta['name'] == 'description'
description = meta['content']
elsif meta['property'] == 'og:url'
url = meta['content']
elsif meta['property'] == 'og:image'
image_url = meta['content']
end
end
if title == ""
title_node = doc.at_xpath("//head//title")
if title_node
title = title_node.text
elsif doc.title
title = doc.title
else
title = param_url
end
end
if description ==""
#maybe search for content from BODY
description = title
end
if url ==""
url = param_url
end
render :json => {:title => title, :description => description, :url => url, :image_url => image_url} and return
end
應用程序/視圖/鏈接/ _form.html.erb:
<div class="form-group">
<%= f.label :url %><br>
<%= f.text_field :url, class: "form-control", id: "post_content" %>
</div>
<div id="preview-title"></div>
我是新來的Rails,並沒有完全理解Ajax,你能告訴我問題在哪裏,爲什麼我的代碼不工作? –
閱讀代碼我找不到任何問題。所以請檢查列表或粘貼JavaScript控制檯日誌和Rails應用程序日誌。如果你不知道如何,請詢問。 –
只需正確寫入routes.rb即可。 –