通过Jquery ajax为datagrid加载数据?

时间:2012-03-14 12:36:16

标签: javascript ajax jquery datagrid

我有这段代码片段(虽然不完整,但忽略了结尾脚本标签)::

<script type="text/javascript">
function gotoa(){
    var h = $.get("http://localhost:8080/2_8_2012/jsp/GetJson.jsp", function(result) {

    });
    alert(result);


var myVar= h;
var storedata={
            identifier:"ID",
            label:"name",
            items: myVar
    };

var store = new dojo.data.ItemFileWriteStore({data: storedata}); 

GetJson.jsp的代码是::

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="MyPackage.PopulateTextbox" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<%

String temp1;
PopulateTextbox obj = new PopulateTextbox();
temp1 = obj.method();
%>

<%=temp1 %>

</head>
<body>


</body>
</html>

我有一个j查询get方法。我传入的URL返回一个Json数组字符串。输出URL ::

[{"ID":1,"Names":"Shantanu","Email":"shantanu.tomar@gmail.com"},{"ID":2,"Names":"Mayur","Email":"mayur.sharma@gmail.com"},{"ID":3,"Names":"Rohit"},{"ID":4,"Names":"Jasdeep"},{"ID":5,"Names":"Rakesh","Email":"rakesh.shukla@gmail.com"},{"ID":6,"Names":"Divyanshu"},{"ID":8,"Names":"hello"},{"ID":9,"Names":"fine"},{"ID":10,"Names":"shivani"}] 

现在我希望这个输出用于我的数据网格,即我希望var myVar应该获得此值,然后它将传递给dojo.data.ItemFileWriteStore。我无法这样做。请帮忙 ?谢谢。

2 个答案:

答案 0 :(得分:0)

$.get()函数是使用$.ajax()函数进行AJAX调用的简写 - 而且,众所周知,AJAX中的第一个A代表异步。如果要使用AJAX调用的响应来执行代码,则需要将该代码放在传递给$.get()的回调函数中。

它可能看起来像这样(虽然没有完整的代码,我不能肯定地说:

function gotoa() {
    var store;

    var h = $.get("http://localhost:8080/2_8_2012/jsp/GetJson.jsp", function(result) {
        var myVar = result;
        var storedata={
            identifier:"ID",
            label:"name",
            items: myVar
        };

        store = new dojo.data.ItemFileWriteStore({data: storedata}); 
            // do whatever with store here, if necessary
    });
}

答案 1 :(得分:0)

修改你的脚本标签:

<script type="text/javascript">
function gotoa(){
    $.get("http://localhost:8080/2_8_2012/jsp/GetJson.jsp", function(result) {
        var storedata={
            identifier:"ID",
            label:"name",
            items: result
             };

            var store = new dojo.data.ItemFileWriteStore({data: storedata});
    });

}
</script>

GetJson.jsp的代码是:

<%@page contentType="application/json" %>
<%@page import="MyPackage.PopulateTextbox" %>
<%
String temp1;
PopulateTextbox obj = new PopulateTextbox();
temp1 = obj.method();
%>

<%=temp1 %>

现在致电gotoa() 它将初始化ajax调用并在回调函数中获取响应