如何在Jquery UI对话框按钮调用上调用Jquery Ajax函数

How do call an Jquery Ajax function on Jquery UI Dialog button call

本文关键字:Jquery 调用 Ajax 函数 按钮 对话框 UI      更新时间:2023-09-26

我只想在jQuery UI对话框的按钮调用上调用一个jQuery Ajax"POST"请求,这是代码片段,

    $("#addqust").dialog({
        autoOpen: false,
        width: 630,
        modal: true,
        resizable: false,
        position: { my: "top", at: "top", of: window },
        buttons: {
            "Save": function (e) {                        
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/InsertQuestion",
                    contentType: "application/json; charset=utf-8",                                                        
                    data: { name: $("#qst").val() },
                    success: function (data) {
                        console.log($("#qst").val());
                        console.log(data.d);
                        // alert("message");
                    }
                    }).done(function (msg) {
                        alert("Data Saved ");
                });
            },
            "Cancel": function () {
                $(this).dialog("close");
            }
        }
    });

但是我得到了以下错误或console.log,并且没有调用PageWeb方法

POST http://localhost:50583/Default.aspx/InsertQuestion 500 (Internal Server Error) 
send 
v.extend.ajax 
$.dialog.buttons.Save 
(anonymous function) 
v.event.dispatch 
o.handle.u

我想知道我犯了什么错误,谢谢你的帮助。

更新WebMethod,这是一种简单的测试方法,

[WebMethod()]
public static string InsertQuestion(string name)
{
    try
    {           
        string strjson;
        strjson = name;
        return strjson;
    }
    catch (Exception ex)
    {
        throw new System.Exception( ex.Message);
    }
}

使用jquery版本,

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js" type="text/javascript"></script>

安装Fiddler并查看流量。你的帖子有一个错误,或者至少服务器返回了500。

http://fiddler2.com/

这里的问题是您的数据对象不是JSON字符串。在ajax调用中试试这个:

buttons: {
        "Save": function (e) {  
            var dataToSend = JSON.stringify({ name: $("#qst").val() });                      
            $.ajax({
                type: "POST",
                url: "Default.aspx/InsertQuestion",
                contentType: "application/json; charset=utf-8",                                                        
                data: dataToSend,
                success: function (data) {
                    console.log($("#qst").val());
                    console.log(data.d);
                    // alert("message");
                }
                }).done(function (msg) {
                    alert("Data Saved ");
            });
        },
        "Cancel": function () {
            $(this).dialog("close");
        }
    }

包括旧浏览器的JSON.js。