1

I want to practice with JSON and AJAX with HTML pages only (no PHP, no asp.NET, no ruby, no Web server locally installed). I want to create web page which will produce JSON data as result for test AJAX request.

Is it possible?

ADDED: Lets change it a bit, suppose that I have a webpage (no asp.net, no php). How to create web page with will output Json data with header set to header('Content-Type: application/json');

Pawel
  • 27
  • 9
  • Nope. If you have no server and no server-side language, what exactly would create the data? You can do it with a static JSON file (which might be just as good for practicing purposes) or you can generate JSON using JS only, but making an AJAX call without anything receiving it doesn't make sense. – JJJ Oct 09 '14 at 06:57
  • possible duplicate of [Origin null is not allowed by Access-Control-Allow-Origin](http://stackoverflow.com/questions/8456538/origin-null-is-not-allowed-by-access-control-allow-origin) – Lee Gary Oct 09 '14 at 08:00

2 Answers2

0

You can give the AJAX request url as "file:///D:/test.txt"

I think IE allows it and Chrome doesn't. And I'm not sure if all versions of IE support it.

Ofcourse this 'response' will be static. It wont change based on your request inputs.

Teddy
  • 4,009
  • 2
  • 33
  • 55
0

JSON are just javascript objects. What you can do is, instead of invoking the real ajax requests, do a mock request that fetch the locally declared json. For e.g.

jQuery (A concrete implementation)

$.get("ajax/test.html", function( data ) {
  console.log(data);
  alert( "Load was performed." );
});

Mock implementation

Create a fake json "factory"

var MockJson = (function () {
  return { "mockObject" : "mockValue" };
})();

console.log(MockJson);

Of course my example is trivial, you can use the response to manipulate the DOM or display the value somewhere.

Lee Gary
  • 2,357
  • 2
  • 22
  • 38
  • Im trying this solution, but MockImplementation should be places in ajax/test.html file,right? TH code should be like this? – Pawel Oct 09 '14 at 07:33
  • U can't access a system file via ajax, there's a cross origin security policy baked into the browser. You can disable that for testing purpose, but the intention of my answer is that, you usually fetch data (json) from server via ajax, why don't you have a mock response from the server and declaring it up front, since you don't have a web server – Lee Gary Oct 09 '14 at 07:35
  • MockJson has to be printed additionally? – Pawel Oct 09 '14 at 07:35
  • You can actually "host" your html file and create a .json file with the json inside and fetch it using ajax. That should work if you really want to retrieve via xmlhttprequest. But for simplicity sake, why not just declare a json object and assume that it's from the server? – Lee Gary Oct 09 '14 at 07:38
  • I change the question a bit. Thanks for answers – Pawel Oct 09 '14 at 07:50