I have an array and I am sending it to a web service,
the url is this
http://localhost:4025/vmp_webservice.asmx/LoadService2Daily?fromDate=2014-05-26+00%3A00%3A00&toDate=2014-05-26+23%3A59%3A01&campaigns%5B%5D=default&campaigns%5B%5D=Support
that url doesn't work and return 500 internal error
but when I remove the %5B%5D, the url becomes this:
http://localhost:4025/vmp_webservice.asmx/LoadService2Daily?fromDate=2014-05-25+00%3A00%3A00&toDate=2014-05-25+23%3A59%3A01&campaigns=default&campaigns=Support
and it works perfectly.
what are these strange characters and how to remove them please?
The array is the selectedCampains and I am sending it like this:
$.getJSON(webServiceUrl,
{ fromDate: valFrom, toDate: valTo, campaigns: selectedCampaigns })
I get that array in this way:
var selectedCampaigns = $("#campaignDiv input:checkbox:checked").map(function () {
return $(this).val();
}).get();
console.log(selectedCampaigns);
OK, these are the square brackets and it has to parsed and removed from URL:
var sc = JSON.stringify(selectedCampaigns);
pass this sc where you're trying to pass selectedCampaigns as an array.
Related
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
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')
EDIT : the API developer provided a solution by using another delimiter and specifying it in the request (see below my answer to my own question)
I am sending POST requests to a RESTful API, which require a comma-separated list of arguments :
var request = require('request-promise'); //promisified npm request
// the list of names is huge
// those names are stored in a MongoDB database
// the namesList is generated programmatically before the request
var namesList = "name1,name2,name3,name4"
var requestOptions = {
method: 'POST',
uri: 'https://myAPI/someEndPoint/',
body: {
key: myAccessKey,
names: namesList
},
json: true
};
request(requestOptions)
.then( () => {_do_something_} );
It works fine for most of the names, but some of them contain a comma :
var arrayNames = ["foo bar", "barfoo", "stupid, comma", "dammit"];
// is converted by my code in :
var namesList = "foo bar,barfoo,stupid, comma, dammit";
This inevitably leads to a wrong list being sent to the API... So, is there a way to "escape" the faulty comma programmatically when I generate the list from the array ?
The long awaited answer from the API developer has arrived (sent an e-mail a while ago), and the solution is as simple as it is efficient : just use another delimiter :
var namesList = "name1;name2;name3;name4" // use ';' instead of ',' here...
var requestOptions = {
method: 'POST',
uri: 'https://myAPI/someEndPoint/',
body: {
key: myAccessKey,
names: namesList,
delimiter: ';' // and specify the delimiter there !
},
json: true
};
request(requestOptions)
.then( () => {_do_something_} );
I don't know if the delimiter field is standard or specific to this API, but it works perfectly for my use case !
You could iterate thru your list that you are sending, enclose comma inside a string with double quotes.
Then handle those double quotes on the server side.
This will preserve your list integrity
use something like this to replace subString:
str = str.replace(/,/g, '","');
On the serverSide, you can then ignore all commas wrapped inside double quotes.
try
var namesList = arrayNames.map(function(val) { return val.replace(',', '\\,');}).toString();
I have the following JSON object data returned from my apicontroller :
[
{"id":2,"text":"PROGRAMME","parent":null},
{"id":3,"text":"STAGE","parent":2},
{"id":4,"text":"INFRA","parent":2},
{"id":5,"text":"SYSTEM","parent":3},
{"id":6,"text":"STOCK","parent":3},
{"id":7,"text":"DPT","parent":3},
{"id":9,"text":"EXTERNAL","parent":null}
]
I want to replace "parent":null with "parent":'"#"'
I have tried the code below, but it is only replacing the first occurrence of "parent":null. How can I replace all "parent":null entries?
$(document).ready(function () {
$.ajax({
url: "http://localhost:37994/api/EPStructures2/",
type: "Get",
success: function (data) {
var old = JSON.stringify(data).replace(null, "'#'"); //convert to JSON string
var new = JSON.parse(old); //convert back to array
},
error: function (msg) { alert(msg); }
});
});
Thanks,
You need to make the replace global:
var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array
This way it will continue to replace nulls until it reaches the end
Regex docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Also, as a side note, you should avoid using new as a variable name as it is a reserved word in javascript and most browsers will not allow you to use it
#JonathanCrowe's answer is correct for regex, but is that the right choice here? Particularly if you have many items, you'd be much better off modifying the parsed object, rather than running it through JSON.stringify for a regex solution:
data.forEach(function(record) {
if (record.parent === null) {
record.parent = "#";
}
});
In addition to being faster, this won't accidentally replace other nulls you want to keep, or mess up a record like { text: "Denullification Program"}.
I'm trying to GET some data from a site using jQuery $.get. I need to set 2 parameters of the same type:
..&q=Some Text&q=Some other text
jQuery appears to be overwriting the first instance of q with the second and only sending 1. Any way around this?
This is the code I was trying to use:
var params = {
"otherParam":"x",
"q":text,
"q":title
};
$.get(url, params, mySuccessFunction);
Try:
var params = {
"otherParam": "x",
"q": [ text, title ]
};
edit — more information: array-valued parameters like that are treated specially by jQuery. To appease many common server frameworks, by default (since release 1.5 or 1.6 I think) those will result in parameter names that include "[]" (open- and close-bracket characters) as a suffix (no number, contrary to my erroneous comment below). If you don't want that, you can set
jQuery.ajaxSettings.traditional = true;
and it'll just be "q" instead of "q[]".
And another way to solve it that does not require encodeURIComponent() or messing with jQuery.ajaxSettings.traditional = true; which I would prefer not to do because I don't want to interfere (even temporarily) with what other parts of the site might be doing simultaneously.
Is:
var params=[
{name:"q", value:title},
{name:"q", value:text}
];
$.get(url, params, mySuccessFunction);
Another approach without modifying jQuery.ajaxSettings.traditional = true; is to use $.param() http://api.jquery.com/jQuery.param/
So something like this:
var params = {
"otherParam": "x",
"q": [ text, title ]
};
$.get(url, $.param(params, true), mySuccessFunction);
You can write the URL like this :
$.get(
url+'?q='+encodeURIComponent(text)+'&q='+encodeURIComponent(title)+'&otherParam='+encodeURIComponent('x'),
mySuccessFunction
);
Things are pretty simple and described in jQuery website http://api.jquery.com/jquery.param/.
First create a params object
var params=[{
name: 'param1',
value: 'hello'
},
{
name: 'param1',
value: 'alex'
}];
next create the data to be sent to the service.
var data = jQuery.param(params);
That object can be inserted as the data param of the ajax request. I like using a settings object
var settings={
url: 'api/domain/timeline',
type: 'get',
contentType: 'application/json',
data: data
};
$.ajax(settings);