【问题标题】:Returning Json to javascript将 Json 返回到 javascript
【发布时间】:2012-09-26 09:25:26
【问题描述】:

我像这样对 ashx 处理程序进行 Json 调用:

    attributes = $("#pageHtmlTag").attr("class").trim();
urlToHandler = 'JSonTestHandler.ashx';
jsonData = '{' + attributes + '}';

$.ajax({
    url: urlToHandler,
    data: jsonData,
    dataType: 'json',
    type: 'POST',
    contentType: 'application/json',
    success: function (data) {
        setAutocompleteData(data.responseDateTime);
        $("body").add("<div>" + data.toString() + " </div>").appendTo(document.body);
        alert("grate suceees");
    },
    error: function (data, status, jqXHR) {
        alert('There was an error.' + jqXHR);
    }
}); // end $.ajax   

我收到并处理它。我还想发回一些要显示的 HTML,但我不知道如何将 html 发回 Jscript。

ashx:

    string jsonData = new StreamReader(context.Request.InputStream, System.Text.Encoding.UTF8).ReadToEnd();

.............................

        var testResultReportString = testResultReport.GetReportHtml();

        var serializer = new JavaScriptSerializer();
        var jSonTestResultReport = serializer.Serialize(testResultReportString);

        context.Response.Write(jSonTestResultReport);

所以问题是。如何将数据返回给 Ajax 调用成功函数?

【问题讨论】:

    标签: asp.net json


    【解决方案1】:

    您可以将数据作为 JSON 对象返回:

    var outputObject = "{ html = '" + jSonTestResultReport  + "' + someOtherData = ... + "}";
    context.Response.Write(outputObject);
    

    并像这样在成功函数中访问它们:

    data.html and data.someOtherData
    

    【讨论】:

    • 它不工作。我在警报弹出窗口中收到错误:语法错误。 Unexpected token = 我发回的输出是: { "resultReport" = "
    • js
    • " }
  • 哦,我想通了。我用 = 而不是 :
  • 【解决方案2】:

    在我这样使用的应用程序中,它在下面我显示所有带有国家/地区ID的状态数据,并且该数据像这样绑定到状态下拉列表..

    StateData objStateData = new StateData();
                LMGDAL.db_LMGEntities dbData = new db_LMGEntities();               
                var data = (from con in dbData.tblStates
                            where con.State_CountryID == ID
                            select new StateData
                            {
                                StateID = con.StateID,
                                StateName = con.StateName
                            }).ToList();
                return data.ToArray(); 
    

    并在该 .ashx 文件中创建一个新类

    [Serializable]
        public class StateData
        {
            public int StateID { get; set; }
            public string StateName { get; set; }
        }
    

    以我的形式

    $("#ddlCountry").change(function () {
                var countryID = $("#ddlCountry").val();
                $.ajax({
                    type: "POST",
                    url: "JsonData.asmx/GetStateByCountryID",
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    data: '{ID:"' + countryID + '"}',
                    success: function (msg) {
                        var data = msg.d;
                        var stateData = "";
                        $.each(data, function (index, itemdata) {
                            stateData += "<option  value='" + itemdata.StateID + "' > " + itemdata.StateName + " </option>";
                        });
                        $("#ddlState").empty();
                        $("#ddlState").append("<option value='0'>-Select State-</option>");
    
                        $("#ddlState").append(stateData);
                    },
                    error: function () {
                        alert('Faild To Retrieve States.');
                    }
                });
            });
    

    我想这会对你有所帮助.....

    【讨论】:

      【解决方案3】:

      您无法返回 AJAX 调用返回的数据,因为您的数据在调用 $.ajax 后无法立即使用,因为它是异步的。您可以返回的是 AJAX 调用返回的数据的承诺。 Promise 是函数的一个很好的抽象:我无法返回数据,因为我还没有数据,我不想阻止并让你等待,所以这里是一个 Promise,你将能够以后使用它,或者只是把它交给其他人并完成它(Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patterns in JavaScript)。例如,而不是:

      $.ajax({
           url: urlToHandler,
           data: jsonData,
           dataType: 'json',
           type: 'POST',
           contentType: 'application/json',
           success: function (data) {
               setAutocompleteData(data.responseDateTime);
               $("body").add("<div>" + data.toString() + " </div>").appendTo(document.body);
               alert("great success");
           },
           error: function (data, status, jqXHR) {
               alert('There was an error.' + jqXHR);
           }
       }); // end $.ajax  
      

      您可以通过编写 Ajax 函数来返回 $.ajax(...) 调用的返回值,例如:

      function testResultReportAjax() {
          return $.ajax({
              url: urlToHandler,
              data: jsonData,
              dataType: 'json',
              type: 'POST',
              contentType: 'application/json',
              error: function (data, status, jqXHR) {
                  alert('There was an error.' + jqXHR);
              }
          });
      }
      

      你得到了你的承诺

      var promise = testResultReportAjax();
      

      然后您可以将其用作函数调用中的参数并使用 AJAX 调用返回的数据:

      promise.success(function (data) {
         alert(data);
      });
      

      您可以查看simple DEMO here。如果需要,请参阅 this answer 以获得更好的解释。

      【讨论】:

        猜你喜欢
        相关资源
        最近更新 更多
        热门标签