在我的rails应用程序中的javascript文件中:我想向我的应用程序发送一个JSON请求,该请求返回一个字符串数组,并在变量中捕获该返回值。
从应用程序的根目录:请求的路径是:'/ employers / get_unique_employer_names.json'
所以如果我处于开发模式:完整的URL将是:
http://localhost:3000/employers/get_unique_employer_names.json
这样的东西但不起作用:
// app/assets/javascripts/application.js
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require turbolinks
//= require_tree .
$(document).ready(function(){
var array_of_names = get: '/employers/get_unique_employer_names.json'
});
答案 0 :(得分:2)
我想你已经注入了jquery
$.ajax({
url: "/employers/get_unique_employer_names.json"
})
.done(function( data ) {
console.log("here is you data", data);
});
并且没有jquery
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
console.log("Here is your data", xmlhttp.responseText);
}
else {
console.log('something else other than 200 was returned');
}
}
}
xmlhttp.open("GET", "/employers/get_unique_employer_names.json", true);
xmlhttp.send();
打开控制台并检查数据
答案 1 :(得分:0)
array_employer_names
未定义,因为它是在您的js文件中定义的,这使得它无法从控制台中看到。这是一个范围的事情。
如果将其更改为
,您将能够在控制台中查看它$.ajax({
url: "/employers/get_unique_employer_names.json"
})
.done(function( data ) {
window.array_employer_names = data
});