Is it possible to use web2py language in javascript file (.js)?
I'm trying to use AJAX with web2py language but I have a problem My code is:
javascript
$(document).ready(function(){
$(".className").click(function(){
jQuery.ajax({
开发者_StackOverflow社区 type:'POST',
url:'getName',
data:{
itemName:'a'
},
timeout: 20000,
success: function(msg) {
alert(msg);
},
error: function(objAJAXRequest, strError){
alert( "Error:" + strError );
}
});
});
default.py
def getName():
itemName=request.vars.itemName
return "Name: " + itemName
The thing is I want to use the data from the database, but is it possible to use
{{for item in tableName:}}
var name={{=item.name}}
like this?
I'm not sure how to extract data from DB in javascript. Can you help me a bit? Cheers
The short answer is that you can't directly extract data from the db in javascript using web2py. You have to query the db with web2py, and then use web2py to send your query data to the javascript (or more accurately since you're using ajax, use jquery/javascript to pull your query data down from web2py). Make sure that you actually need to perform logic on the client (javascript) side here, because the easiest thing to do would be to perform all your logic in python in the web2py controller.
However, if you do for some reason need to perform logic on your data on the client side, then you are on the right track. The easiest thing for you to do would be fetch the records you need from the db in the web2py controller, then package the records up as a json object in your web2py controller ("import simplejson" or you can do it with the standard library with the latest version of python), then return that json object to make it available for your js to fetch using the ajax request you've included above. Only at that point should you loop through the json object using the javascript to get the data you need.
That said, if you're just trying to get a field from a single record from the database, the easiest thing to do would be just to query the database correctly to get that record, and return it in a web2py controller for your ajax script to get.
精彩评论