Question just like the title.
In command line, we can type:
curl -H "header_name: header_value" "http://example"
to navigate to http://example with a custom request header as shown above.
Q: If I need to write a JavaScript to do the same thing, how should I do?
var url = 'https://example';
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url ,false);
myRequest.setRequestHeader('header-name','header-value');
myRequest.send();
I tried this code, there is no syntax error but the page didn't change. Hence, I don't really know if I modified the request header(s).
Here is how you can handle this:
var req = new XMLHttpRequest();
req.open('GET', 'http://example', true); //true means request will be async
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
//update your page here
//req.responseText - is your result html or whatever you send as a response
else
alert("Error loading page\n");
}
};
req.setRequestHeader('header_name', 'header_value');
req.send();
Related
I am trying to return a webpage, and grab the part of the page labeled: Description. I want to be able to split the returned HTML, but with the "" that are in HTML it will not work correctly.
This is for a template to allow a user on an extension to be able to add a pre-loaded string to fill in a box. I have tried splitting the string at a set word, but my knowledge does not extend past trying to use the string.
function pullWebpage(){
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
var response = this.responseText;
response.split("Description");
console.log(response);
}
});
xhr.open("GET", "https://jira2.cerner.com/browse/ION-25843?", true);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
}
I want to be able to successfully pull out the description of the page pulled in the GET, and use this to set up an automatic template. HTML returned in GET using postman here
While the issue before was based on grabbing the whole HTML, using the rest api was a better solution. Changing the code to:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
var response = JSON.parse(this.responseText);
console.log(response.fields.description);
}
});
xhr.open("GET", "https://jira2.cerner.com/rest/api/2/issue/ION-25843");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data);
Allows for the code to go out and grab the json of the page, and then grab the specific definition of the page.
I wrote a function that fetches the guid of a lookup field and uses that to make an AJAX call. This is the the call that I made:
fetchOptionSet: function (executionContext) {
var formContext = executionContext.getFormContext(); //get form context
var client = Xrm.Page.context.getClientUrl(); //get client url
var childId = formContext.getAttribute("new_childid").getValue()[0].id;
var child = childId.replace(/[{}]/g, "");
var contract;
var req = new XMLHttpRequest();
req.open("GET", client + `/api/data/v8.2/new_childallergieses(${child})?$select=_new_childid_value`, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var result = JSON.parse(this.response);
var _new_childid_value = result["_new_childid_value"];
contract = _new_childid_value.replace(/[{}]/g, "");
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
However, I get a bad request every time that the script runs. I need the guid returned by the call (contractid) to make another ajax call! The uri is fine,I tested the link in the browser and it returns the contractid that I want.
First issue Bad request can be solved by replacing GUID value childId for any {}.
Second issue, this is Ajax call which is asynchronous by mentioning true in req.open, hence you may have some other issue with request uri. That’s why readyState is undefined.
Try this. Take your uri & paste in browser address bar to see any clear error.
http://test.crm.dynamics.com/api/data/v8.2/new_childallergieses(guid)?$select=_new_childid_value
Changed from Asychronous to Sychronous and all of a sudden it worked!
var path_one = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/new_childallergieses(" + child + ")?$select=_new_childid_value";
req.open("GET", path_one , false);
I did some investigating and realized that the function is set to execute on load, and sending an asynchronous call on load gives a bad request.
Hi, I am trying to extract something from an API, which should return me a string with the recent prices for Ethereum.
After that I would like to parse the string and drop all data, so that only the latest price is returned.
This is the code I have so far, however it does not return anything and I am stuck on this and how to parse the code.
Any help is greatly appreciated! Thanks.
{
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.kraken.com/0/public/Ticker?pair=ETHEUR', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}
}
};
You're not sending the request. You need to add xhr.send(); to send the request. Here is the sample request.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.kraken.com/0/public/Ticker?pair=ETHEUR', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(this.responseText);
}
};
xhr.send();
After creating your xhr and adding the proper callbacks to it, make sure to invoke xhr.send(). The response from that endpoint seems to be a JSON object, so you can invoke JSON.parse() on the response to turn it into a javascript object that you can work with.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.kraken.com/0/public/Ticker?pair=ETHEUR', true);
xhr.onreadystatechange = function() {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// Parse JSON response
var data = JSON.parse(xhr.responseText);
// Use the object however you wish
console.log(data);
}
}
xhr.send();
You must call the xhr.send(); function to actually send the request. Otherwise you have just initialized the request and also set up the callback function to handle the response but no request to the API is sent.
I am new to Javascripting.
I have http webservice URL which results in xml respose. how do I get the response xml from the URL. I tried using the following using XMLHttpRequest but no luck.
function send_with_ajax( the_url ){
var httpRequest = new XMLHttpRequest();
//httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
httpRequest.open("GET", the_url, true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
httpRequest.setRequestHeader("X-Alt-Referer", "http://www.google.com");
httpRequest.send();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4)
{
var _tempRecommendations = httpRequest.responseXML;
window.alert(httpRequest.response)
window.alert(httpRequest.responseText)
window.alert(_tempRecommendations)
}
};
};
I always get httpRequest.readyState = 1 and also when I evaluate the response in console its all null.
According to this: Ajax won't get past readyState 1, why?, you should try to replace your onreadystatechange event by an onload event:
httpRequest.onload= function() {
if (httpRequest.readyState == 4)
{
var _tempRecommendations = httpRequest.responseXML;
window.alert(httpRequest.response)
window.alert(httpRequest.responseText)
window.alert(_tempRecommendations)
}
};
If it doesn't work, try to simplify your code, start with a very basic request like shown here: http://www.w3schools.com/xml/xml_parser.asp for example.
Then start adding request headers, to see which instructions break your program.
You can also check the webservice by calling it directly in the browser to make sure that the problem comes from your side
I'm using a Javascript to ask our app (which is in Google App Engine) if the file a user wants to upload is already in his list of files (he will overwrite).
I know how to send the request, but how can I create a response from the server, using Python?
This is the request:
var req = new XMLHttpRequest();
req.open('POST', 'https://safeshareapp.appspot.com/upload', async);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", body.length);
req.setRequestHeader("Connection", "close");
if (async) {
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var response = null;
try {
response = JSON.parse(req.responseText);
} catch (e) {
response = req.responseText;
}
callback(response);
}
}
}
// Make the actual request
req.send(body);
As you see, we are getting the responseText from the request after everything has gone OK, but my question is how do we fill that responseText field on the server side??
class MyRequestHandler(webapp.RequestHandler):
def get(self):
import json
result = {"filename": xxx} // just an example, result can be any Python object
json_obj = json.dumps(result)
self.response.out.write(str(json_obj))