Am not able to access my xml file which is inside js folder thru the url function inside collections.How to link to this url to retrieve data?
Once you've setted up the path to your file, you'll have to call fetch on the collection. like so:
var Things = backbone.Collection.extend({ url: "path/to/my/file" });
var things = new Things();
things.fetch().done(function() {
console.log( things.toJSON() );
});
Although, this only works with JSON data format. For XML, you'll need to override collection's parse method to return a javascript object from the XML.
Related
I am working with two Express JS applications one is an API and second is application that is using this API by making requests and displaying received informations to user.
In API route I'm sending image as response:
router.get('/:customer_id',authController.isAuthenticated,(req,res) => {
.
. Retrieving customer data
.
return res.sendFile('/uploads/'+foundCustomer.doc_path);
});
And later another application is getting this document:
router.get('/:customer_id',(req,res) => {
var options = {
url: 'http://'+config.API.user+':'+config.API.password+'#'+config.API.host+':'+config.API.port+'/customers/'+req.params.customer_id
};
request(options,(err,response,body)=>{
return res.render('customer/show',{
document: ?, // Send document as parameter to view
});
});
});
In this point I want to render customer/show(EJS view engine) with customer document, but I don't want to save this document in my application files, because document is only needed to display in view (customer details and document are stored in another application).
I was trying to create temporary directory in my application structure, but it is difficult to manage deleting those not needed documents (Application has many users and at the same time many customers can be displayed).
Another solution that I was trying to implement is to make Ajax request on client side and latter append received document to <object data='document'>. But this request has to be authenticated with user and password, so I realised that storing credentials on client side javascript is not the best idea...
I am not sure that is it even possible to render and display image without saving in application files?
I would be grateful for any help, maybe the best workaround is to somehow manage temporarily saved documents.
Why not create a File object inside EJS template then use that for src attribute on an <img> ? You're already getting the raw buffer/blob from your image API server. Store it inside template.
From https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
// place this code (store this variable) inside of your EJS template
// so it can be used by the client-side JS
var aBlob = new Blob( array[, options]); // Where array is the raw buffer data returned from your image API server
See https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
var objectURL = URL.createObjectURL( aBlob ); // Where object is a Blob object
See https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
const img = document.createElement('img');
img.src = objectURL;
Final solution (tested), using axios to make API request:
In my route I'm going to make HTTP request to my API to retrieve PDF file(document):
axios.get(`http://my-api/customer/id`).then(response => {
var photo = new Buffer(response.data, 'binary').toString('base64');
return res.render('customers/show',{
document: document
});
});
In my ejs view, I'm using HTML object tag to display received PDF:
<object data="data:application/pdf;base64,<%-document%>"></object>
I have an index that creates randomly generated dynamic content.
So everytime you load the index, it'll create a series of view that are dependent on what my Rails model has produced and sent to Backbone.
From backbone, I am curious what I could do to "refresh" the page without doing something like this :
window.location = '/'
I'd like to do it within Backbone.. something like this :
Backbone.history.navigate('/', {trigger: true, replace: true});
But this doesn't necessarily send a new request to the url.
All I would need to do to accomplish my goals is send a GET request to /, which should return a JSON object I can pipe through the rest of my Backbone app.
Is there a way to send this request within Backbone? Or should I just go a traditional jQuery route, and just make a $.get request?
Since your REST api returns a JSON object, simply use a Backbone.Model to structure this data. You can then bind events to do whatever you like in your application.
var RandomData = Backbone.Model.extend({ url: '/' });
var randomData = new RandomData();
// Here, `Backbone` can be substituted by any `View`, `Collection`, `Model...
Backbone.listenTo( randomData, 'change', function() {
//Do something everytime this changes.
});
// When you need to issue a GET '/' request. The following will put the
// JSON response inside of `randomData.attributes`
randomData.fetch();
I've started using Newtonsoft.Json.Schema.JsonSchemaGenerator along with various property attributes over in my C# code to help keep my client script DRY. What I'd like to do is create a default initialized object client-side based on the schema from the server. This would be useful for, say, when the user clicks 'New Foo' to add a new entry into a table.
Obviously I can just code it up to iterate the .Properties and build up the new object, which is what I'm doing at the moment. However I'd prefer to avoid reinventing any wheels.
Are there any JS libraries for working with JSON schema that will do this, among other nifty things I've yet to realize I need?
1/29/2013 UPDATE
Some people have attempted to answer my question and have been off base, and as a result have received some negative feedback from the SO community. So let me attempt to clarify things. Here is the challenge:
In JS client script, you have an object that represents the JSON Schema of another object. Let's say, this came from the server via JSON.NET and is the representation of a C# class.
Now, in the JS client script, create one of these objects based upon the JSON Schema. Each field/property in the object must be default initialized according to the schema, including all contained objects!
BONUS: Bind this new object to the UI using MVVM (eg Knockout). Change some of the fields in response to user input.
Send this new object to the server. The server-side code will add it to a collection, database table, whatever. (Yes, the object will be sent as JSON using Ajax -- we can assume that)
No duplication! The only place where the class is defined is in the server-side code (C# in my example). This includes all metadata such as default values, description text, valid ranges, etc.
Yes there is (I tried it with NodeJS):
JSON Schema defaults
Link updated.
i think...you have to use two way binding with your HTML code...so, once your client side change you will get on your costume js file.
check here for knockout js.
Knock Out JS Link
and on C# code use : $("#urlhidden").val() OR Document.GetElemenyByID("#urlhidden").val().
here you will get array/list or textbox value
Use json with Ko
create new viewmodel for knockout js which you will get the idea about on above link.
and create a json call
like:
self.LoadMAS_Client = function () {
try {
var params = { "clientID": ClientId };
$.ajax({
type: "POST",
url: "http://" + ServerString + "/Services/LogisticsAppSuite-Services-Web-Services-MasClientService.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
// in response u will get the data.and use as per your requirement.
eg. self.SelectedClient(response.your value);
},
error: function (ErrorResponse) {
}
});
}
catch (error) {
}
};
================================New Update ==========================================
i think..one way you can do...get data on xml format at C# code and covert into json string...check below code // To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
I need to call a web service from javascript that returns a JSON array in the following format:
["hello","there","I","am","an","array"]
Unfortunately, the javascript library I'm using (Sencha Touch) to load this data into a widget doesn't accept that format as data input. It will work with something like this however:
[["hello"],["there"],["I"],["am"],["an"],["array"]]
So there are two questions here-- how can I call that web service in javascript and then manipulate the returned array into the format I need? I've been looking at jQuery's getJson() method, not sure if that's the way to go or if there are better ways.
The URL that delivers the JSON array is this right here. Thanks for your help.
Here's a jsFiddle showing both parts of what you asked about. I'm using jQuery for my AJAX call (faked in the jsFiddle) and I'm using Underscore.js for the manipulation:
http://jsfiddle.net/JohnMunsch/E7YTQ/
// Part 1: Get the raw data. Unfortunately, within a jsFiddle I can't go get it from a different domain. So I'm
// simulating the call instead.
var rawDataPromise = $.ajax({
url : "/echo/json/",
data : fakeData,
type : "POST"
});
// var rawDataPromise = $.ajax("http://fastmotorcycleservice.cloudapp.net/FastMotorCycleListService.svc/list/Bruno");
rawDataPromise.done(
function (results) {
// Part 2: Manipulate the data into the form we need.
var manipulatedResults = _.map(results, function (item) { return [ item ]; });
console.log(manipulatedResults);
}
);
// You could also pull that together into a single call $.ajax(...).done(function (results) { ... });
once you have the data in one of your local variables you can manipulate it as you want:
var data = the_function_you_use_to_get_data();
var formatted_array = new Array();
for(i in data){
var d = new Array();
d[0] = i;
formatted_array.push(d);
}
i hope it answered your question
Here is a collection I define in backbone.js
var List=Backbone.Collection.extend({
model: Item,
url: "TodoApp/index.php/todo"
});
var list=new List
Then I created a Model in the collection with an ID=80
Now, when I do list.fetch();
It will make a call to
"TodoApp/index.php/todo/80"
However, at the backend, using Codeigniter, I really need to have
TodoApp/index.php/todo/get/82.........where get is a function I defined to access DB
So, should I change the Collection url to "TodoApp/index.php/todo/get"
But again, that's not really where the resource is located?
In route.php try:
$route['todo/(:num)'] = "todo/get/$1";
HERE is what I ended up doing.
I renamed the index of the controller to resource
therefore using a URL of:
TodoApp/index.php/todo/resource
When getting a GET request at
TodoApp/index.php/todo/resource/80
extract the second segment of the URI and read from DB with that.