无法对Json Web服务进行Ajax调用

时间:2012-10-09 12:37:23

标签: jquery ajax json

我想调用一个返回JSON对象的Web服务,Web服务规范如下面的链接所示:

http://dev.joget.org/community/display/KB/JSON+API#JSONAPI-web%2Fjson%2Fworkflow%2Fpackage%2Flist

我在asp.net mvc3 Web应用程序中有一个简单的视图,如下所示:

@{
    ViewBag.Title = "Home Page";
}
   <script src="@Url.Content("~/Scripts/f.js")" type="text/javascript"></script>


<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
<h1>The Processes are </h1>

<ul id="products"/>

以及以下f.js来调用Web服务并显示返回的JSON数据:

$(document).ready(function() {
    $.ajax({
        type: 'GET',
        url: 'http://localhost:8080/jw/web/json/workflow/package/list?loginAs=admin',
        dataType: 'json',
        success: function(data) {
            $.each(data, function(key, val) {
                alert("jsonData");
                // Format the text to display.
                var str = val.packageId + ': $' + val.packageName;

                // Add a list item for the product.
                $('<li/>', {
                    text: str
                }).appendTo($('#products'));

            });
        }
    });
});​

但问题是,当我导航到视图时,由于AJAX调用,视图上不会显示任何内容,请记住,如果我手动输入URL:'http:// localhost:8080 / jw / web / json / workflow / package / list?loginAs = admin'在浏览器的地址栏中,结果会在浏览器中成功显示吗?

那可能会出现什么问题?

:::修订:::

我将JavaScript更新为以下内容:

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "http://localhost:8080/jw/web/json/workflow/package/list?loginAs=admin",
        dataType: "JSONP",
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            $.each(data, function(key, val) {

                // Format the text to display.
                var str = val.packageId + ': $ ' + val.packageName;

                // Add a list item for the product.
                $('<li/>', {
                    text: str
                }).appendTo($('#products'));

            });
        }
    });
});​

但是Web服务调用的结果返回为:

- undefined: $ undefined

而不是:

 {"activityId":"","processId":"289_process1"}

那么阻止我的代码显示正确数据的问题是什么?

1 个答案:

答案 0 :(得分:-1)

我将我的JavaScript代码修改为以下内容: -

//code goes here
success: function(result) {
$.each(result.data, function(key, val) {

//code goes here