简体   繁体   English

如何使用Ajax成功在新选项卡中打开URL?

[英]How To Open URL In New Tab Using Ajax Success?

Here i am trying to open the file in new tab by calling ViewFile action of Doctor controller using Ajax Success which is in function abc(this) on click of anchor tag. 在这里,我尝试通过使用Ajax Success调用Doctor控制器的ViewFile动作来打开新选项卡中的文件,该动作在单击锚标记时位于函数abc(this)
Now the problem is that everything is as required but the url doesnot open in new tab. 现在的问题是,一切都按要求进行,但URL在新选项卡中没有打开。

Below is my Ajax 以下是我的Ajax

<script>
function abc(thisEvent) {
    debugger;
    var getDoCredId = $(thisEvent).attr('docCredId');
    var parameter = { id: getDoCredId };
    $.ajax({
        url: "/Doctor/ViewFile1",
        type: "get",
        dataType: "html",
        data: parameter,
        success: function (data) {
            debugger;
            if (data = true) {
                debugger;
                var getdoctorId = $(thisEvent).attr('docCredId');
                var url = "/Doctor/ViewFile/" + getdoctorId;
                window.open(url, "_blank");
            }
            else {
                debugger;
                showNotification("Error", "warning");
            }
        }
    });
}


Below is my anchor tag HTML 以下是我的锚标签HTML

<a title="View Attachment"   docCredId = "' + getDocCredId + '"  onclick="abc(this)"><i class="btn btn-web-tbl btn-warning fa fa-eye "></i></a>



Below is code behind 下面是代码

public bool ViewFile1(int id)
    {
        var document = _doctorService.GetDoctorCredentialDetails(id);
        string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
        string strFileFullPath = Path.Combine(AttachPath, document.AttachedFile);

        string contentType = MimeTypes.GetMimeType(strFileFullPath);
        bool checkFileInFolder = System.IO.File.Exists(strFileFullPath);
        if (checkFileInFolder == true)
        {
            return true;
        }
        else
        {
            return false;
        }
  }
    public ActionResult ViewFile(int id)
    {
        var document = _doctorService.GetDoctorCredentialDetails(id);
        string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
        string strFileFullPath = Path.Combine(AttachPath, document.AttachedFile);
        string contentType = MimeTypes.GetMimeType(strFileFullPath);
        bool checkFileInFolder = System.IO.File.Exists(strFileFullPath);  
        bool filedata = System.IO.File.ReadAllBytes(strFileFullPath).Any();
        byte[] filedata1 = System.IO.File.ReadAllBytes(strFileFullPath);
        var cd = new System.Net.Mime.ContentDisposition
        {
            FileName = document.FileName,
            Inline = true
        };
        Request.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString());
        return File(filedata1, contentType);
    }

Since this is too long for a regular comment, I am posting this as an answer, although it isn't directly going solve the problem because I am not able to reproduce it, but might give some insights and let you check the differences with what happens in your code as compared with this simplified example. 由于这对于常规评论来说太长了,因此我将其发布为答案,尽管它不能直接解决问题,因为我无法重现该问题,但可能会提供一些见解,并让您检查与哪些方面的差异与此简化示例相比,您的代码中发生了错误。


Calling window.open() from jQuery ajax success callback works just fine: https://codepen.io/nomaed/pen/dgezRa 从jQuery ajax成功回调中调用window.open()很好用: https : //codepen.io/nomaed/pen/dgezRa

I used the same pattern as you did, without your server code but using jsonplaceholder.typicode.com sample API instead. 我使用了与您相同的模式,没有服务器代码,而是使用jsonplaceholder.typicode.com示例API。


There are some issues with the code sample that you might want to consider, even though you didn't ask for comments about it and it's not directly related to your issue (probably): 即使您没有要求对其提出评论并且它与您的问题没有直接关系(可能),您仍可能要考虑代码示例中的一些问题:

  1. if (data = true) means data will always be true. if (data = true)表示数据将始终为true。 You probably mean to do a if (data === true) if you know it's a boolean value, or if (data) if you want to accept any truthy value (true, {}, "something", 42, etc). 如果您知道它是布尔值, if (data)可能意味着执行if (data === true) ,或者如果您想接受任何真实值(true,{},“ something”,42等), if (data === true)可能是if (data === true) )。 Judging by the Java code and how you define the response format in the jQuery ajax call, it looks like you're expecting the "data" variable result be an HTML and not a boolean. 从Java代码以及如何在jQuery ajax调用中定义响应格式来看,您似乎期望“数据”变量的结果是HTML,而不是布尔值。 You might want to try and remove the dataType: "html" row and let jQuery set the data format according to what is coming back from the server, and/or send a JSON formatted response, as in a POJO of { result: true } for a successful response. 您可能想要尝试删除dataType: "html"行,并让jQuery根据服务器返回的内容来设置数据格式,和/或发送JSON格式的响应,例如在{ result: true }的POJO中获得成功的回应。 Then make sure that data.result === true to be sure that you got what you expect. 然后确保data.result === true ,以确保您获得了期望的结果。

  2. You should probably add arbitrary data to tags DOM elements the data-* attributes and if you're using jQuery, access them using the .data() selector. 您可能应该向data-*属性的 DOM元素标签添加任意数据,如果使用的是jQuery,请使用.data()选择器访问它们。 White adding just random attributs with string values may work, it's considered an abuse of the HTML and DOM, and the data-* attributes are there specifically for adding any data. 只添加带有字符串值的随机属性的白色可能会起作用,这被认为是对HTML和DOM的滥用,并且data-*属性专门用于添加任何数据。

  3. In the abc() function you grab the value of the attribute in the beginning ( var getDoCredId = $(thisEvent).attr('docCredId'); ) but in the callback you're trying to get the value once more. abc()函数中,您从一开始就获取属性的值( var getDoCredId = $(thisEvent).attr('docCredId'); ),但是在回调中,您尝试再次获取该值。 You really don't need it since the success() callback is a closure in the scope of the abc() function and it has access to the value already, so doing var getdoctorId = $(thisEvent).attr('docCredId'); 您真的不需要它,因为success()回调是abc()函数范围内的闭包,并且已经可以访问该值,因此执行var getdoctorId = $(thisEvent).attr('docCredId'); in the callback is really not needed. 确实不需要回调。

  4. I'd also suggest naming getDoCredId variable just as docCredId . 我还建议将getDoCredId变量命名为docCredId Having a "get" prefix usually means that it's a getter function or a reference to some getter. 具有“ get”前缀通常意味着它是一个getter函数或对某些getter的引用。 Likewise, the " thisEvent " argument of the main function should probably be called " callerElement " or something like that since it's not an event, it's an actual element that you're passing directly from the DOM when calling abc(this) in the onClick event handler of the <a> anchor. 同样,主函数的“ thisEvent ”参数可能应该称为“ callerElement ”或类似的名称,因为它不是事件,它是在onClick中调用abc(this)时直接从DOM传递的实际元素。 <a>锚点的事件处理程序。 This is just to make the code clearer to understand for anyone who's reading it, and for yourself when you're coming back to it several months in the future and trying to figure out what's going on :) 这仅仅是为了使代码更清晰易懂,以供正在阅读它的任何人以及您自己在未来几个月重新使用它并试图弄清正在发生的事情时了解自己的方法:)

Try adding async: false to your Ajax request 尝试向您的Ajax请求添加async: false

function abc(thisEvent) {
    debugger;
    var getDoCredId = $(thisEvent).attr('docCredId');
    var parameter = { id: getDoCredId };
    $.ajax({
        async: false, // <<<----------- add this
        url: "/Doctor/ViewFile1",
        type: "get",
        dataType: "html",
        data: parameter,
        success: function (data) {
            debugger;
            if (data = true) {
                debugger;
                var getdoctorId = $(thisEvent).attr('docCredId');
                var url = "/Doctor/ViewFile/" + getdoctorId;
                window.open(url, "_blank");
            }
            else {
                debugger;
                showNotification("Error", "warning");
            }
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM