jquery ajax error {“readyState”:0,“responseText”:“”,“status”:0,“statusText”:“error”}

后端 未结 4 644
逝去的感伤
逝去的感伤 2020-12-17 15:07

I am trying to do an ajax request

$.ajax({
  type: \"post\",
  url: \"download.php\",
  error: function(data, status, err){
           alert(JSON.stringify(d         


        
4条回答
  •  情话喂你
    2020-12-17 16:07

    I came across the same issue: how to register every time a user click the link.

    The problem is infact that if you don't stop the pop up, the ajax request doesn't complete and you get readyState: 0!

    I've done another version of the above that maybe is more readable (even if more verbose)

    /*  --------------------------------------------------------------------------
     *  Before that add 'downloads' class to every anchor tag (link) in your page
     *  This script does the rest
     *  
     *  remember to change 'your_php_file' with the one you use
     *  -------------------------------------------------------------------------- */
    
    $(document).ready( function()
    {
    
        // Check if there is any link with class 'downloads'
        if ( typeof $('.downloads') != 'undefined' )
        {
            var links = $('.downloads');
    
            // Run this for every download link
            for ( var i = 0; i < links.length; i++ )
            {   
                // Set click behaviour
                links[i].onclick = function(e)
                {
                    // Get download name
                    var attr = this.attributes,
                        href = attr.href.textContent,
                        elem = href.split('/'),
                        elem = elem[elem.length - 1];
    
                    // Send the download file name and only after completing the request let the user download the file
                    $.ajax(
                    {
                        type : "POST",
                        dataType : "text",
                        // 'your_php_file' must be an ABSOLUT or RELATIVE path!
                        url: your_php_file,
                        // 'elem' is a variable containing the download name
                        // you can call it in your php file through $_POST['download_name']
                        data: { download_name: elem },
                        // here we go magic:
                        // after the request is done run the popup for the download
                        complete: function()
                        {
                            window.location.href = href;
                        }
                    });
    
                    // Stop default behaviour until ajax request has been done
                    e.preventDefault();
                };
            }
        }
    });
    

提交回复
热议问题