suppose I have a config javascript file:
window.Config = {};
Config.UI = {
"Area": {},
"Layer": {},
"Sprites": {},
"Audio": {}
};
Config.UI.Area = {
"prop": {
"uuid": {
"_type": "string",
},
"frame": {
"_type": "rect",
"_value": {
"x": "0",
},
"_aka": "frame"
},
"zIndex": {
"_type": "string",
}
},
then I want use $.ajax to read this file:
$.ajax({
url:'js/config.js',
success:function (data, textStatus) {
console.log(data);
}
})
the question is how can I get some key's value in the config,by use the data $.ajax return?
like the "Config.UI" or the 'uuid' in ui.area.prop?Or can I convert them to json?
Rather than use AJAX, why not just insert a script?
var script = $('<script>');
script.attr('type', 'text/javascript');
script.attr('src', 'js/config.js');
script.bind('load', function() {
// use window.Config
});
script.appendTo('head');
icktoofay has a good suggestion, and the issue with the jQuery.ajax call looks to be a missing dataType: 'script' option which will evaluate the response and should give you object access. You might want to look into jQuery.getscript() as well.
I find it very useful and powerful to store data on the server as javascript objects and read them using Ajax. And it is very easy to do. Let me give you an example from an educational application I have written.
This is an example table of contents file (l1contents.js) that I would store on the server:
{
title : "Lesson 1",
topics : [
{name : "Topic 1", file : "l1t1data.js" },
{name : "Topic 2", file : "l1t2data.js" },
]
}
This is the javascript code I use to process the file:
$.ajax({
url : contentsFileName, // would be set to 'l1contents.js'
dataType : 'text', // yes this is correct, I want jquery to think this is text
cache : false,
success: function(data) {
var contentsObj = eval('(' + data + ')');
var lessonTitle = contentsObj.title;
for (var i = 0; i < contentsObj.topics.length; i++) {
var topic = contentsObj.topics [i];
// process topic.name and topic.file here
}
}
});
Obviously, this is simplified, but hopefully you get the idea. I simply use eval to set the object. And note that I don't even need any javascript code defining the structure of contentsObj. (I, of course, do have extensive comments defining the structure of my objects, but they are simply comments, not code.)
if your json file contains json data than you can use parseJSON() , toJSON() method.
and another solution is use eval(), this conver json data to javascript object so you can easly get a value by giving key.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an API that returns JSON like this:
[{
"Code": "001",
"Name": "xyz",
"Members": [{
"FullName": "User1"
}]
}, {
"Code": "002",
"Name": "asd",
"Members": [{
"FullName": "User2"
}]
}]
I want to replace Name and member in my label matching with "Code" and i want to do that with ajax. How can achieve the matching with Code?
This is my implementation:
$('#btnFind').on('click', function () {
var Code = $("#input_edit_code").val();
$.ajax({
type: "get",
url: "/mvc/ComplaintHandlerSquadGetListPage",
success: function () {
alert();
},
error: function (ex) {
alert(ex.title);
}
});
})
You can use javascript's filter and map Array's functions.
Let's pretend you store the code typed by the user inside this codeNumber var
var codeNumber = '002';
Your array of members:
var members = [{"Code":"001","Name":"xyz","Members":[{"FullName":"User1"}]},{"Code":"002","Name":"asd","Members":[{"FullName":"User2"}]}];
A function to filter your array by Code :
var byCode = function(member) {
return member.Code === codeNumber;
};
A function to get the name of the filtered member :
var getName = function(member) {
return member.Name;
};
You get the member's name
var memberName = members.filter(byCode).map(getName).toString();
console.log(memberName);
I don't believe AJAX and simple JSON alone can do what you want.
JSON is a way to structure objects - JavaScript Object Notation. It only structures data.
AJAX is an Asynchronous means of making an HttpRequest. It asks a server for something.
If you use AJAX to ask for a JSON file. You will get the JSON data.
I believe you have two options:
Use AJAX to request the data from the server. The server will then have to load the JSON file, find the correct data and return the correct data to AJAX.
Use AJAX to get the JSON data. Find the correct data with JavaScript.
Inside the success handler, you can compare something like this:
success: function(response) {
// yourObject that matches the code
var yourObject = response.filter(function(item) {
return item.Code === Code
});
// wherever you want to show this name
$("body").text(yourObject.Name);
}
$.ajax({
type: "get",
url: "/mvc/ComplaintHandlerSquadGetListPage",
success: function (result) {
jQuery(result).each(function(i, item){
if(item.Code == Code)
{
$('#myid').text(item.Name);
}
},
error: function (ex) {
alert(ex.title);
}
});
How do I add multiple HTTP headers dynamically in an AJAX call?
I have an array of objects containing which headers to add and their values like:
[
{
"headerName": "foo",
"headerValue": "bar"
},
{
"headerName": "some",
"headerValue": "text"
},
{
"headerName": "random",
"headerValue": "values"
}
]
I want to iterate over the array and add headers with its corresponding values in my AJAX call.
$.ajax({
url: 'foo/bar',
...
headers: {
'key[0]':'value[0]',
'key[1]':'value[1]',
(to n times)
},
...
});
I can use jQuery and Knockout in my project. Please help.
Thanks in advance.
In jQuery you can try something like:
headers = {}
$.each(array,function(i,val){
headers.key[i] = array[i].headerValue;
})
Or maybe this should work:
headers = {}
$.each(array,function(i,val){
headers.key[i] = val["headerValue"]; //since val is a JSON object here.
})
I haven't tried executing this code, you can refer to this for help.
I'm trying to add users to a Custom Audience in Facebook, and I believe I have bungled the payload piece of the request below.
The error returned is:
(#100) Missing required parameter: payload
For reference, I'm generating the hash using Crypto-JS. Here's the code I tried:
var payload = { "payload": [{ "schema": "EMAIL_SHA256", "data": [hash] }]};
FB.api('/000000000/users', 'post', payload, function (response) {
if (response && !response.error) {
alert("This worked");
} else {
alert(response.error.message);
}});
The FB.api documentation shows that it expects 'payload' as a JSON object (https://developers.facebook.com/docs/marketing-api/custom-audience-targeting/v2.3#add). I just haven't been able to figure out the correct syntax yet. The example in the Facebook API documentation shows the following:
payload = {"schema":"EMAIL_SHA256","data":["HASH", "HASH", "HASH" ]}
Here's what I have so far (not working):
var payload = { "payload": [{ "schema": "EMAIL_SHA256", "data": [hash] }]};
Can anyone assist with the syntax? I've found plenty of examples of JSON objects and arrays, but I haven't seen anything that matches this format:
payload = {"schema":"EMAIL_SHA256","data":["HASH", "HASH", "HASH" ]}
For the benefit of any other JS/JSON novices, I finally figured it out after more experimentation:
var payload = { "payload": { "schema": "EMAIL_SHA256", "data": [hash] } };
I have a json url that returns data in the format
{
"photos" : [
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
}
I'm using the json in a javascript function, and need to manipulate it to remove the root key. i.e. I want something that looks like
[
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
I've been hacking around with various approaches, and have referred to several similar posts on SO, but nothing seems to work. The following seems like it should.
var url = 'http://path/to/my/json/feed.json';
var jsonSource = $.getJSON( url );
var jsonParsed = $.parseJSON(jsonSource);
var jsonFeed = jsonParsed.photos
What am I doing wrong?
A couple of issues there.
That's invalid JSON, in two different ways. A) The : after "photos" means that it's a property initializer, but it's inside an array ([...]) when it should be inside an object ({...}). B) There are extra " characters in front of the images keys. So the first thing is to fix that.
You're trying to use the return value of $.getJSON as though it were a string containing the JSON text. But $.getJSON returns a jqXHR object. You need to give it a success callback. That callback will be called with an object graph, the JSON is automatically parsed for you.
Assuming the JSON is fixed to look like this:
{
"photos": [
{
"id": 1,
"image": "https://path/to/my/image/1.jpg"
},
{
"id": 2,
"image": "https://path/to/my/image/2.jpg"
}
]
}
Then:
$.getJSON(url, function(data) {
var photos = data.photos;
// `photos` now refers to the array of photos
});
I am new to web and I need to get JSON object for a webpage that has data displayed this:
{
"expires": "2011-09-24T01:00:00",
"currencies": {
"BZD": {
"a": "2.02200",
"b": "1.94826"
},
"YER": {
"a": "220.050",
"b": "212.950"
}
}
I tried use jquery's $.getJSON to get the object but it didn't work.
<script>
$.getJSON("http://m.somewebsite.com/data",
{
format: "json"
},
function(data) {
document.getElementById('test').innerHTML = data;
});
</script>
I am wondering how to get this information correctly?
In order for this to work, you need to define jsonp, jsonp allows you to gain read access to another site's document, as the alternate version is barred.
$.getJSON("http://m.somewebsite.com/data?callback=?", { format: "json" }, function(data) { document.write(data); });