问题
I am trying to create a dynamic HTML table using javascript. I have written a small function to add rows to the table on the fly. However the individual cells themselves should be gsp tag elemets. In the example below I am trying to use the autoComplete tag provided by the grails-UI plugin. Even though I set the innerHTML of the cell to the gsp tag, it is not being rendered on the page.
function addIngredientRow(tableName,element){
var table = document.getElementById(tableName);
var lastRow = table.rows.length;
var row = table.insertRow(lastRow);
var leftCell = row.insertCell(0);
var autoCompleteDiv = document.createElement('div');
leftCell.appendChild(autoCompleteDiv);
autoCompleteDiv.innerHTML= '<gui:autoComplete id="autoCompleteIngredient" resultName="ingredients" labelField="name" idField="id" controller="recipe" \
action="getIngredientAsJSON" forceSelection="true" \
useShadow="true" width=60px queryDelay=0.5 />';
var rightCell = row.insertCell(1);
var autoCompleteDivR = document.createElement('div');
rightCell.appendChild(autoCompleteDivR);
autoCompleteDivR.innerHTML= '<p>test</p>';
}
The HTML snippet invoking this code is as follows:
<tr>
<td>
<gui:autoComplete
id="autoCompleteIngredient"
resultName="ingredients"
labelField="name"
idField="id"
controller="recipe"
action="getIngredientAsJSON"
forceSelection="true"
useShadow="true"
width=60px
queryDelay=0.5
/>
</td>
<td>
<div onclick="addIngredientRow('createRecipeTable',this)"><img alt="Add Ingredient" src="${resource(dir:'images/icons',file:'Add16.png')}" ></div>
</td>
</tr>
I have checked that the javascript is being invoked by putting an alert. So all the wiring is fine. I think that the issue is with resolving the gsp tags by the browser. How can I invoke gsp tags from javascript??
回答1:
GSP pages are rendered on the server, long long long before the browser EVER gets hold of the html and can start running the Javascript. You'd need to use an AJAX call to send the gsp tag back to the server, where it can (hopefully) be rendered into HTML, then take the HTML from the AJAX response and insert it into your document.
回答2:
GSPs are evaluated prior to rendering to the browser. If you want javascript to use them, the javascript source will have to be served/evaluated by the grails engine.
You can create a controller for the js, and use a gsp to render it like any other page of your grails application.
来源:https://stackoverflow.com/questions/6998006/using-gsp-tags-from-javascript