简体   繁体   English

在Javascript文件中发送JSON HTTP Get请求

[英]Sending JSON HTTP Get Request within Javascript File

From within a javascript file in my rails application: I want to send a JSON request to my application, which returns an array of strings, and capture that return value within a variable. 从我的Rails应用程序中的一个javascript文件中:我想向我的应用程序发送一个JSON请求,该请求返回一个字符串数组,并在变量中捕获该返回值。

From the root of the application: the path to the request is: '/employers/get_unique_employer_names.json' 从应用程序的根目录开始:请求的路径为:'/employers/get_unique_employer_names.json'

So If I'm in development mode: the full url would be: 因此,如果我处于开发模式:完整的URL将是:

http://localhost:3000/employers/get_unique_employer_names.json http:// localhost:3000 / employers / get_unique_employer_names.json

Something like this but it doesn't work: 像这样的东西,但是不起作用:

// 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'
});

I suppose you have injected jquery 我想你已经注入了jQuery

$.ajax({
  url: "/employers/get_unique_employer_names.json"
})
.done(function( data ) {
    console.log("here is you data", data);  
});

and same without jquery 和没有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();

Open console and check for your data 打开控制台并检查您的数据

array_employer_names is undefined because it is defined in your js file, which make it unvisible from console. array_employer_names是未定义的,因为它是在您的js文件中定义的,这使得它在控制台中不可见。 it's a scope thing. 这是一个范围的东西。

you'll able the view it in your console if you change it to 如果将其更改为,则可以在控制台中查看它

$.ajax({
  url: "/employers/get_unique_employer_names.json"
})
.done(function( data ) {
    window.array_employer_names = data
});

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

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