I am building an angular app with a rest endpoint as back-end. I already have my data in a json file and my data is almost static and not that big. Is it possible to let angular directly query on this JSON file, instead of relying on the remote rest endpoint?
Solution:
I have used linqjs for my purpose and it works great. Thanks.
You can query it directly using $http.get or an equivalent call. It works the same as any other $http call, except you obviously can't post, put, or delete.
$http.get('mydata.json')
.success(function(data) {
$scope.mydata = data;
});
Related
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');
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.
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.
I'm developing an API where if the user specifies the action with .json as a suffix (e.g. admin/users.json), they get the response in the return of json, otherwise they get a regular html View.
Some actions may not have a json response, in which case they would just return a html View.
Does anyone have advice on how this can be implemented cleanly? I was hoping it could be achieved via the routing.
I suggest you to create your application as an api.
Foreach page, you need two controllers. Each controller use a different route (in your case, one route ending by .json, and one without).
The json controller return data in json form. The "normal" controller call the corresponding json route, deserialize the json, then pass the resulting array to the view.
This way, you've got a standardized api (and maintained, because your own app use it) available, as well as a "normal" website.
More information:
Consuming my own Laravel API
Edit: Maybe it's doable with a filter, but I'm not sure about that and I don't have time to try it myself right now.
In Laravel 5.x, to implement both capabilities like sending data for AJAX or JSON request and otherwise returning view template for others, all you have to do is check $request->ajax() or $request->isJson().
public function controllerMethod(Request $request)
{
if ($request->ajax() || $request->isJson()) {
//Get data from your Model or whatever
return $data;
} else {
return view('myView.index');
}
}
I have an Asp.Net MVC3 application that use embedded RavenDB to store data.
The view needs json data that is now created by the controller in this way:
public ContentResult Data()
{
var res = JsonConvert.SerializeObject(DocumentSession.Query<DataObject>());
return new ContentResult { Content = res, ContentType = "application/json" };
}
Everything works fine but to me it seems inefficient because data that are stored in DB in JSON format is serialized in POCO and then deserialized again.
Is there a more direct way to get json data directly from the embedded db?
It's not inefficient at all. Keep in mind that internally, raven actually uses BSON - so you would have to translate it anyway. Also there are metadata fields. If you were to return it directly through your controller, you would have no opportunity to shape the response of the data and strip off the unwanted fields.
If you must continue with this line of thinking, you have two options:
You could use the DocumentStore.DatabaseCommands.Get() and related operations to return RavenJObjects that you could then translate JSON from.
You could talk directly to the Raven database over HTTP without using the raven client.
Neither of these are straightforward, and you are throwing away a lot of goodness of the Raven Client API. IMHO, any performance gain you were to achieve would be unnoticeable. I would stick with your current approach.
Also - If you are just trying to avoid having to serialize here, consider returning a JsonResult instead of a ContentResult. If you want to use Json.Net instead (per your other recent post), Here is a cleaner way to do it: http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx
I am following the tutorial in the CakePHP book that explains the basics of setting up a RESTful web service.
So far, I've updated my routes file to the following:
Router::mapResources('stores');
Router::parseExtensions('json');
I have also setup a blank layout in app/layouts/json and the appropriate json views. I am receiving my json output successfully when I navigate to controller/action.json
I am wondering though, without the.json extension it attempts to load the regular view. I am looking to build a pure api with only json output, is there any way to prevent regular render output instead?
You could force a rendering as JSON if you can recognise a JSON request another way. For example, if the Accepts HTTP header contains application/json, you could put this in your controller:
public function beforeFilter(){
if ($this->request->accepts('application/json')) {
$this->RequestHandler->renderAs($this, 'json');
}
parent::beforeFilter();
}
It's CakePHP 2.0 notation, but something similar probably exists for CakePHP 1.2 and 1.3.
You could also detect the request Content-Type instead, or as well, especially if Accepts is not used.
What are you seeing at the moment? If you've used bake Cake may have generated the views for you?
Just delete the views in /app/views/layout and /app/views/controllername
If you are trying to prevent the request from hitting the controller at all then I'm not so sure, you could just update your .htaccess file to only send requests ending in .json to the app or something similar.
here is what i did.
if i know i'm building only json API, i added to my AppController.php following:
public function beforeFilter()
{
if (empty($this->request->params['ext']) || $this->request->params['ext'] != "json")
{
$this->render(FALSE, 'maintenance'); //no view, only layout
$this->response->send();
$this->_stop();
}
}
and in my /app/Layouts/maintenance.ctp
echo __('Invalid extension');
this way all requests without the json extension will end up on the "maintenance" page where you can put any info you want, i'm planning to put there link to API docs.
I'm trying to deal with: "Requests made from Javascript running on your web pages must be proxied to avoid same-origin policy conflicts."
I know how to work with the JSON once I've got it. But aside from copy-pasting the JSON results via my browser, I don't know how to localize it for use.
Did you tried
$.getJSON('url', function(data){
//do smth with data
})
?
After the request is complete, data will be an object with all JSON response and you can access it as regular js object: data.something and so on.