Using JavaScript, I want to retrieve the content of the script files. These script files remain in local(in web page).
For example.
In web page, there is a script,
<script src="tool.js"></script>
Latter, I want to get the content of tool.js and process the retrieved result (like dump its content).
I have tried to use jQuery.getScript. However, it tells me that Origin null is not allowed by Access-Control-Allow-Origin.
try an ajax like the following
$.ajax('/tool.js', {
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function(data) {
console.log(data);
},
error: function() {
console.log("call failed");
}
});
You need to configure your Access-Control-Allow-Origin:
Access-Control-Allow-Origin: *
This lets you use any resource to obtain assets from an external domain. Do this first and either Mahan's or Lars's solution will work.
More info:
Access-Control-Allow-Origin Multiple Origin Domains?
try using jquery.load() and put its contents on an element and use .html()
<html>
</head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
//setup ajax to work locally
$.ajaxSetup({
crossDomain: false,
isLocal :true
});
$("#a").load('jquery.js', function() {
alert($("#a").html());
});
});
</script>
</head>
<body>
<span id="a" style="display:none;"></span>
</body>
</html>
Browser Check:
the code above works and tested in FF, Safari, Opera and IE
but if you keep on having problem with Origin null is not allowed by Access-Control-Allow-Origin then having a web server installed is needed as said here; Origin null is not allowed by Access-Control-Allow-Origin
Reference:
http://api.jquery.com/load/
code for your disposal : http://jsfiddle.net/PeaH3/1/
Related
I am working on a project in which I'm in need to get the data stored in XML file using javascript or jQuery. My Script code is
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST", //I also tried POST method
url: "match.xml",
dataType: "xml",
success: function(data){
$(data).find("mchdata match").each(function(){ //match is a tag
$(".container").append('<div class="head">'+ $(this).attr("src") +'</div>'); //src is an attribute of match tag.
});
},
error: function(){
$(".container").text("Error occured");
}
});
});
</script>
Html code is
<body>
<div class="container"></div>
</body>
Every time I run this code it's showing 'Error occurred' message in container div. I tried to inspect the page, it shows an error message like
Failed to load file:///C:/Users/vinay%20Dahiya/Desktop/match.xml:
Cross origin requests are only supported for protocol schemes: http,
data, chrome, chrome-extension, https.
I don't know what does it mean. Is this the right script url 'm using
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
I'm trying to solve this for last 2-3 days but don't know what actually wrong in the code
XML file is View XML file
Thanks in advance.
I'm suggesting a quick fix for this, since you are testing this on a local machine and nowhere near production,
go to the folder where the xml is and start a simple python server there.
use
python -m SimpleHTTPServer
then you can access your file using,
http://localhost:8000/xxyy.xml
I'm trying to grab some tracking information from a website and tried to use load and ajax but I'm getting the following errors:
XMLHttpRequest cannot load http://www.tuffnells.co.uk/PODLookupResults.aspx?__EVENTTARGET=&__EVENTARGU…%24tbDestPostcode=AL15BY&ctl00%24maincontent%24btnDoPODLookup=Search+Again. No 'Access-Control-Allow-Origin' header is present on the requested resource.
What I have tried:
<div id="tracking"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#tracking").load( "http://www.tuffnells.co.uk/PODLookupResults.aspx?__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATEGUID=7ca82b1d-b722-4cdc-b74a-b338d8577ffa&__VIEWSTATE=&__EVENTVALIDATION=%2FwEdAAevVXD1oYELeveMr0vHCmYPaomE%2FDwQD43eOdzEj3p%2Fm4U4pgxq6tlupSJfQZQBazFFj%2F1LmlGLyHFagz1yHZm8bjowVgAJ8C3e%2B2bVMPt91KjXCHjnAsonQDi2zFSuasUVzpitHiLDCDtiLHCjNCQG4CxrbV5VPFqBeOgs2X52AD%2FEb%2BYR%2BEJ68PaN2CiyKzE%3D&ctl00%24ctl16%24tbHeaderSearch=Search..&ctl00%24maincontent%24tbAccountRef=01484267&ctl00%24maincontent%24tbConsignmentRef=2837&ctl00%24maincontent%24tbDestPostcode=AL15BY&ctl00%24maincontent%24btnDoPODLookup=Search+Again #ctl00_maincontent_pnlPODRecords" );
});
</script>
and
<div id="tracking"></div>
<script type="text/javascript">
$(document).ready(function(){
var url = "http://www.tuffnells.co.uk/PODLookupResults.aspx?__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATEGUID=7ca82b1d-b722-4cdc-b74a-b338d8577ffa&__VIEWSTATE=&__EVENTVALIDATION=%2FwEdAAevVXD1oYELeveMr0vHCmYPaomE%2FDwQD43eOdzEj3p%2Fm4U4pgxq6tlupSJfQZQBazFFj%2F1LmlGLyHFagz1yHZm8bjowVgAJ8C3e%2B2bVMPt91KjXCHjnAsonQDi2zFSuasUVzpitHiLDCDtiLHCjNCQG4CxrbV5VPFqBeOgs2X52AD%2FEb%2BYR%2BEJ68PaN2CiyKzE%3D&ctl00%24ctl16%24tbHeaderSearch=Search..&ctl00%24maincontent%24tbAccountRef=01484267&ctl00%24maincontent%24tbConsignmentRef=2837&ctl00%24maincontent%24tbDestPostcode=AL15BY&ctl00%24maincontent%24btnDoPODLookup=Search+Again";
$.ajax({
url:url,
type:'GET',
success: function(data){
$('#tracking').html($(data).find('#ctl00_maincontent_pnlPODRecords').html());
}
});
});
</script>
Anyone have any ideas? I need to get the tracking details into our tracking page as they don't provide a API.
Answers staring right at you!
No 'Access-Control-Allow-Origin' header is present on the requested resource.
It's not possible with Javascript, use PHP instead :
$.ajax({url: 'loadRemoteFile.php', type: 'POST', data: {loadPage: url}, success: function(data){
doStuff();
}});
and your PHP file :
if (isset($_POST['loadPage'])){
echo file_get_contents($_POST['loadPage']);
I found the link which may be helpful for you i think.
Thanks
I have made an Ajax call to Bing to get its daily image, however i get an error in the console:
this is the full code its on a localhost using wamp
index.php
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
$.ajax({
url : "http://bing.com/HPImageArchive.aspx?format=js&idx=0&n=1",
dataType:"jsonp",
});
function mycallback(data)
{
$('#output').html(data.images[0].url);
}
</script>
I think you should study the documention for jquery ajax call.
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
(function() {
var bingImagesUrl = "http://bing.com/HPImageArchive.aspx";
$.getJSON( bingImagesUrl, {
idx:0,
n:1,
format: "js"
}).done(function( data ) {
$('#output').html(data.images[0].url);
});
})();
</script>
#Below_the_Radar: your answer does not really help as OP is likely getting the same error even if he makes the Ajax call correctly.
According to Is there a way to get Bing's photo of the day?, it seems that Bing.com only supports XML, JSON, and RSS. I guess OP want to make the call with dataType: "jsonp" probably because he would like to bypass the browsers same-origin policy.
This can be solved client-side in browser by using a Chrome extension, but I guess that is not OP's use case. I bet OP is trying to get a picture from Bing's archive and thus use it in his own website. If that is the case, it has no solution as we need to have "Access-Control-Allow-Origin": "*" in the response's headers returned by Bing, which we do not have control.
I suggest considering an alternative. Try this: https://source.unsplash.com/
I need to parse a content that is dynamically generated by a javascript from a remote page.
For example, I need to get the price from this page: http://www.alibaba.com/product-detail/BRG-Newest-Fashional-Protective-Case-For_1666645206.html#J-wrapper
but the price is generated by a javascript, so when I download the page with ajax, it downloads only the html file without the results of the scripts.
So I tried to embed in the background an iframe and then parse the document inside this iframe, but there is a security issue that doesn't let me parse it.
Do you know if there is another way I can do it?
The function that I use is this:
$.ajax({
url: url,
dataType: 'text',
success: function(html, _, xhr) {});
but the resulting HTML is without the scripts information, so the price is empty.
I tried to use also:
<html lang="en">
<head>
<meta charset="utf-8">
<title>contents demo</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<iframe src="http://api.jquery.com/" width="80%" height="600" id="frameDemo"></iframe>
<script>
document.getElementById("frameDemo").onload = function() {
var contents = $( "#frameDemo" ).contents();
}
</script>
</body>
</html>
but I get this error:
Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement':
Blocked a frame with origin "null" from accessing a frame with origin "api.jquery.com".
The frame requesting access has a protocol of "file", the frame being accessed has a protocol of "http".
Protocols must match.
Instead of using an iframe, try using a chrome app webview. It will run in a segregated container without the restrictions you referenced. But you can still communicate with it.
I mentioned i read the suggested link ...and Could not able to understand the
suggestion .."Use Greasemonkey to modify Pages and start writing some
javascript to modify a web page
I am loading a text file with $.ajax. When running the code on Firefox, I get the following error:
Error: ["Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)" location: "<unknown>"]
Here's my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
$.ajax({ url: "demo_test.txt",
success: function (result) {
$("#div1").html(result);
},
error: function (abc) {
alert(abc.statusText);
},
cache:false
});
return false;
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
I've already read the following questions:
firefox reading web page from local JS file -- access to restricted URI denied, code: 1012, nsresult: NS_ERROR_DOM_BAD_URI
Error: [Exception... "Access to restricted URI denied" .... while calling $.ajax method
It was suggested that file system should not be used, so changed the URL to http://demo_test.txt, but that did not solve the issue.
I also heard that it might be because of a cross domain issue. If so, what exactly is meant by that, and how should I solve the problem?
Browser security prevents the code from running. You are better off running a local server such as IIS or Apache.
You can change your browser to run local content by changing a browser config
Firefox
Go to about:config
Find security.fileuri.strict_origin_policy parameter
Set it to false
I finally seems to Get it working . Here is working Script
$("button").click(function(){
$.ajax({url:"http://localhost/demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});
Workaround : put the html file and text file on local server (IIS) New Site .