问题
I have a page, when loaded, calls a Document.ready jQuery script, which, using today's date as an input, sends an AJAX request to a PHP script to query the database for any "entries" with that date. If it finds some, they are added to a array, then JSON encoded and returned to the jQuery script, which then, in a for loop, spits out a <div>
per "entry" using JSRender templates. These <div>
s live inside a form.
There is a button to create a new "entry" which when pressed just clones the last "entry", wipes it clean, gives the inputs arrays (input name="TI[new1][ ]") a new index (the 'new1' bit) and appends it under the last one (within the form). When form is submitted another AJAX request is made to write/update the database.
What I cannot quite figure out is how to reload the form when a new entry has been made, so that it gets current plus new entries with their correct ids, as at present the form submits, but of course does not refresh, so the entries still have the "newx" id rather than the one they have now been assigned when written to the database.
<form>
<div id="empty-for-jsrender-output">
</div>
<script (template for jsrender)></script>
</form>
<script src="get-entries"></script>
// get-scripts
calls ajax with var for current date
returns json array
for each nested array, calls jsrender script, which spits out a div block per entry within #empty-for-jsrender-output
So how do I make the form or #empty-for-jsrender-output reload like it does when the page is first loaded for the first time after I submit the form with a new entry?
Sorry, edit, forgot to add that I have tried this in my submit-entry js script in the ajax.done section:
$.getScript("assets/js/getEntries.js");
to try and run the same script again that runs when the page is actually reloaded (which works). But all this does is empty the div...it is not populating it again.
回答1:
I won't try to propose details of how to do that - since it involves specific application choices.
But for the overall approach, I would encourage you to use JsViews, not just JsRender, so you can get incremental updates of the UI thanks to observable data changes and data binding.
Then, for your AJAX scenario, a great approach is to use the new compiled View Models feature in JsRender/JsViews, and call the merge()
method on your data when you get the updated JSON data returned from the second and subsequent AJAX requests.
Here are some documentation links:
- http://www.jsviews.com/#jsvmodel
- http://www.jsviews.com/#viewmodelsapi@merge
- http://www.jsviews.com/#jsvviewmodelsapi@mergesample
来源:https://stackoverflow.com/questions/37351409/jsrender-and-ajax-and-php