If I use the params for pass a list in GET method:
fetch_physicalserver_list(){
var params = {
id_list: this.physicalserver_id_list // there is [24, 26, 27]
}
this.$Lml_http('get', this.$Api_urls.user_productmanage_physicalserver.list(), params, response => {
this.physicalserver_list = response.data.results
console.log( response.data.results)
}, error => {
})
}
And in the request, the id_list convert to the id_list[]=24&id_list[]=27&id_list[]=27.
and I don't know how to get the id_list in the backend.
I use the method to get the id_list[] I will only get the first id, if I get id_list, I will get nothing.
the code of get_param_from_query_params method:
def get_param_from_query_params(query_params, param):
param_temp = None
try:
mutable = query_params._mutable
query_params._mutable = True
param_list = query_params.pop(param)
param_temp = param_list[0] if (isinstance(param_list, list) and len(param_list) > 0) else ''
query_params._mutable = mutable
except Exception as e:
pass
return param_temp
So, I have two questions:
1.The params's id_list converted to id_list[]. where is the official description?
2.How can I get the id_list after I passed to the backend?
Firstly, you are using the key id_list[], so you must use id_list[] to retrieve the key in Django. Including [] in JavaScript is a convention to show there are multiple values, but it makes no difference to Django.
If you want a list of values instead of a single value, then use pop_item instead of pop.
It's not clear to me why you need the get_param_from_query_params method. You are returning param_list[0] which means you'll only ever get a single item. It would be much simpler to use getlist:
id_list = query_params.getlist('id_list')
Related
I am not sure if this is an issue about VueJS or JS itself.
I have string in my DB (converted JS Object with JSON.stringify() ) which looks like this:
{"type":5,"values":{"7":"/data/images/structured-content/64-7-scico.jpg","8":"<b>wefwe</b>","9":"Nějaký text","10":"/data/images/structured-content/64-10-scico.jpg"}}
What I wanted to do is select it from database (via Axios), convert it back to JS object and set it to VueJS data:
.then(response => {
if (response.data.response === "ok" && response.status == 200) {
// get data
let data = response.data.data.data[0];
// pass name to state
this.objectName = data.name;
// get json in string format
let result = data.content;
// first log
console.log(result);
// convert string to json
let content = JSON.parse( result );
// second log
console.log( content.values );
// update states
this.IDType = content.type;
this.values = content.values;
}
})
Axios, data.name and content.type works fine, however the second log (content.values) seems to be returning observer with empty strings which I can't pass to Vue data and work with it, as you can see on the screen below, values in this object are just empty no matter what I do.
What is exactly wrong in here? Thank you!
from debugger:
To be reactive Vue needs to know what the keys of an object are before you assign them. So if they are known, pre assign them:
data : () => ({
values : {
7 : "",
8 : "",
9 : "",
10 : ""
}
}),
Then use object assign to set them:
Object.assign(this.values, content.values)
If the keys are unknown / dynamic values you can set them to be reactive using the $set method:
Object.keys(content.values).forEach(
function(key){
this.$set(this.value, key, content.values[key])
}
)
So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply
I am trying to retrieve the value attribute of an unsubmitted input field as parameter to a URL that opens/saves an excel file. The Parameters are supposed to be used to filter the excel file.
I have tried using a for()-loop to save the parameters into an array and then proceed to use the append() method to add them to the end of the url.
Code below shows how I am trying to singularly append each parameter one after the other
var url = new URL("file:database/reports/getCurrentStorageOverview.php?params=excel");
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
search_params.append('params', $("#searchParameter1").val());
search_params.append('params', $("#searchParameter2").val());
search_params.append('params', $("#searchParameter3").val());
search_params.append('params', $("#searchParameter4").val());
url.search = search_params.toString();
var new_url = url.toString();
window.open("database/reports/getCurrentStorageOverview.php?params=excel");
console.log(new_url);
The parameters are supposed to be added to the end of the url however the console keeps telling me the value attribute is either undefined/ when i was trying to use an array it was filling the array with 4 "undefined(s)"
it's a different aproach but since i haven't tested your method i can show u what i normally use for this case:
const querify = obj => {
return Object.keys(obj)
.map(key => {
if (typeof obj[key] === 'object') {
return querify(obj[key])
} else {
return `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`
}
})
.join('&') }
what this does is it takes an object like
var filters = { page: 1, length: 10, sortBy: 'id', etc... }
and turns it into a query string that looks like "page=1&length=10&sortBy=id" etc so u can use it like this:
var url = `database/reports/getCurrentStorageOverview.php?${querify(filters)}`
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
I'm retrieving an OSM Json from an overpass call, to obtain a list of features that I have to save on a database. Since the data are very different from one another (for example, some of them do have a a tag called "addr:city", and some of them not), I would like to check if a key exists, and only in that case save the corresponding value. I've found only this question but it's not my case, since I do not know a priori which keys one element will have and which not, and since I'm working with a great load of data, I really can't check the elements one by one and of course I can't write an IF for each case.
Is there a way to solve this? I was thinking something about "if key has null value, ignore it", while looping over the elements, but I don't know if something like that exists
EDIT:
This is my query:
https://overpass-api.de/api/interpreter?data=[out:json][timeout:25];(node[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696);way[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696););out%20center;
and this is the code I'm using to save the data on firebase:
results.elements.forEach(e=>{
var ref = firebase.database().ref('/point_of_interest/');
var key = firebase.database().ref().child('point_of_interest').push().key;
var updates = {};
var data = {
città: e.tags["addr:city"],
tipologia: e.tags["amenity"],
indirizzo: e.tags["addr:street"],
nome: e.tags["name"],
lat: e.lat,
lon: e.lon
}
updates['/point_of_interest/'+key] = data;
firebase.database().ref().update(updates);
})
"results" is the response in json format
You could use something like that:
var attrs = ["addr:city", "amenity", "addr:street", "name"];
var labels = ["città", "tipologia", "indirizzo", "nome"]
var data = { };
attrs.forEach((a, i) => {
if (e.tags[a]) { data[labels[i]] = e.tags[a]; }
});
You could even make this more dynamic, if you can query the attribute names and labels from somewhere.