javascript - Ajax success() 可以处理两种类型的返回吗?

标签 javascript c# jquery asp.net ajax

使用 JavaScript/Jquery/jqGrid 处理 C# ASP.NET 项目。

新任务是让一个页面 i) 接受 Excel 输入文件,ii) 使用列 ID 查找其他信息,以及 iii) 使用输入文件中的某些列和从返回的所有列生成新的 Excel 文件数据库。

我已经完成了,但只想做更多的错误处理。在存储过程中,如果一切正常,它会返回一个数据表(或者在 Oracle 术语中,一个 CURSOR)。如果出现错误,我添加了一个 catch block 并返回错误消息。

我修改了 AJAX 调用。除了添加 dataType 作为“text”之外,我还希望返回 XML 形式。

$.ajax({
    // POST
    // URL: url to call that stored procedure
    dataType: text,
    success: function (response) {
        // now the response is XML (don't know why... 
        // specify dataType as 'text', but get XML...)
        // If response contains 'string' tag, report error.
    },
    failure: ...
})

这就是我以前所做的。我没有指定数据类型,但不知何故它有效。

$.ajax({
    // POST
    // ... rest is same but without the dataType
    success: function (response) {
        Download( response )
        // The file is already and placed in Download directory. 
        // Call 'Download()' will actually make the download happen
        // But here response is just a path to the Download directory +
        // download file name.

下载()是:

function Download(url) {
    document.getElementById('my_iframe').src = <%=ResolveUrl("~/")%> +url;
    return false
};

如何让成功函数处理这两种类型的响应?

(供您引用:前端页面是 ASP.NET。单击按钮将调用 JavaScript 函数。该函数通过 $.ajax() 调用 Web 服务函数。由于行数较多,Web 服务函数多次调用数据库类中的函数 - 每次仅传入一个 ID。该函数将返回调用存储过程。)

<小时/>

编辑:感谢 Mustapha Larhrouch 提供的解决方案。以下是我需要调整的几点:

  1. 添加数据类型。
  2. 如果响应是 XML,请检查是否有错误。
  3. 如果不是 XML,只需下载。

这是我的代码:

$.ajax({
    // POST
    // URL
    dataType: "text",
    success: function (response) {
        if (isXML(response)) {
            var xmlDoc = $.parseXML(response);
            $xml = $(xmlDoc);
            var errMsg = $xml.find("string").text();

            if (errMsg != "" ) {
                // pop up a dialog box showing errMsg
            }
        } 
        else {
            Download(response);
        }

最佳答案

如果解析了响应,您可以检查响应是否是 xml,如果不是,则响应是字符串。您可以使用此函数检查响应是否为 xml:

function isXML(xml){
    try {
        xmlDoc = $.parseXML(xml); //is valid XML
        return true;
    } catch (err) {
        // was not XML
        return false;
    }
}


$.ajax({
    // POST
    // ... rest is same but without the dataType
    success: function (response) {
        if(isXML(response){
            Download( response )
        }
        else{
           //report as error
        }

关于javascript - Ajax success() 可以处理两种类型的返回吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45284595/

相关文章:

javascript - 我怎样才能更多地组织我的代码以防止不良行为?

javascript - lodash 包含多个参数

javascript - 使用 Web 蓝牙 API 获取广告数据

c# - 在 DataGridView 中禁用列标题排序的最佳方法

c# - Monotouch : Setting Window in pre 5. 0 设备

javascript - 在javascript中单击另一个按钮后激活按钮

javascript - .hover 在与 .html 一起使用时不起作用

c# - 向字符串数组添加新值的更好方法?

jquery - 引导轮播的进度条

javascript - 使用 JavaScript 进行 HTML5 验证