【问题标题】:Calling ajax request from html page inside asp.net project从asp.net项目中的html页面调用ajax请求
【发布时间】:2015-07-17 14:38:31
【问题描述】:

我无法从我的 Visual Studio 项目中的 html 页面获取简单的 ajax 示例。它可以在网络表单 (aspx) 中正常工作:

... webform1.aspx 和 form1.html ...

function ShowCurrentTime() {
            alert("before json");
            $.ajax({
                type: "POST",
                url: "json.aspx/GetCurrentTime",
                data: "{name: bob }",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }

            });
            alert("after json");
        }

        function OnSuccess(response) {
            alert(response.d);
        }

... webform1.aspx 和 form1.html ...

<input id="btnGetTime" type="button" value="Show Current Time"
                   onclick="ShowCurrentTime()" />

... json.aspx ...

[WebMethod]
        public static string GetCurrentTime(string name)
        {
            return "Hello " + name + Environment.NewLine + "The Current Time is: "
                + DateTime.Now.ToString();
        }

如果我将代码放在 webform1.aspx 中,它可以正常工作。如果我把它放在 form1.html 上,json.aspx 不会返回任何内容。我正在使用 vs2013 从我的机器上以调试模式运行项目。任何帮助将不胜感激。

更新 #1

我检查了提琴手,服务器返回以下结果(500):

{"Message":"Invalid JSON primitive: bob.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at ...

【问题讨论】:

  • form1.html 和 webform1.aspx 是否在同一目录下?
  • 在浏览器中打开开发者工具并在 Javascript 控制台中查找任何错误
  • form1.html 是否加载 jquery.js?
  • 是的,form1.html和webform1.aspx在同一个目录下。是的,jquery 已经加载,通过调用 if (window.jQuery) { // jQuery is loaded alert('jquery is loaded'); 来确认}
  • 检查了Firefox浏览器控制台,按下按钮时控制台中没有任何错误。我只是得到之前/之后的警报。在 IE 中也试过。

标签: asp.net ajax json


【解决方案1】:

您的 json 格式错误。字符串需要用引号引起来。将bob 放在引号中,您应该会很好。我不确定为什么它可以在 ASP.NET 页面上运行,除非它有引号。

function ShowCurrentTime() {
        alert("before json");
        $.ajax({
            type: "POST",
            url: "json.aspx/GetCurrentTime",
            data: "{name: \"bob\" }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }

        });
        alert("after json");
    }

    function OnSuccess(response) {
        alert(response.d);
    }

【讨论】:

  • 伙计,我觉得自己很笨。谢谢朋友。
  • 当它是一个愚蠢的错误而不是需要数周时间重新编码的东西时会更好:)
猜你喜欢
  • 2013-06-07
  • 2020-04-22
  • 1970-01-01
  • 2012-05-02
  • 2021-04-09
  • 1970-01-01
  • 2019-06-10
  • 1970-01-01
  • 2017-03-06
相关资源
最近更新 更多