繁体   English   中英

Ajax Post 请求不适用于移动设备

[英]Ajax Post request not working on mobile devices

我遇到一个问题,我在 jQuery 中的.on('click')事件后向服务器发送 Ajax post 请求,但 Ajax 请求在移动设备上不起作用。 在桌面设备上它工作得很好。 这让我做了一些研究。 我发现的第一个问题是点击事件可能无法在触摸屏设备上注册,但这不是问题所在。 当我在移动设备上触摸按钮时发出一些警告消息后触发了触摸事件。 在 iOS 和 Android 设备上触发的是触摸事件,而不是 Ajax 请求。 我还添加了touchstart以确保事件会在触摸设备上触发。 我研究的另一个潜在问题是,如果您没有指定在发布请求后从服务器返回的预期数据类型(纯文本、json 等……),iOS 和 Android 设备上可能会出现一些问题。 我指定了数据类型,但请求仍然存在问题。 最后,我看到可能存在一些缓存问题,所以我将缓存参数设置为 false 并在标头中指定了no-cache 这也没有解决问题。 对于我尝试的每个“修复”,Ajax 请求仍然在桌面设备上完美执行,但在移动设备上却不行。 正如我所提到的,其中的点击事件本身已在移动设备上注册,因为当我在 Ajax 请求之前发出警报时,它们会显示在移动设备上。 但是,Ajax 请求本身不会执行。 下面是我的代码:

$('.crop_image').on('click touchstart', function(event){
    alert("Triggered"); //Event triggered on mobile devices
    $image_crop.croppie('result', {
        size: 'viewport',
        format: 'png',
        type: 'blob'
   }).then(function (blob){
        $form = $('#uploadForm');
        var fd = new FormData($form);
        fd.append('upload_image', blob);
        $.ajax({
            url: "handle-image.html",
            type: "POST",
            data: fd,
            processData: false, //processData false
            contentType: false, //contentType false
            dataType: "text",  //response will be text
            cache: false,  //cache false
            headers: {
                "cache-control": "no-cache" //set headers
            },
            success: function (data){
                alert("Upload Successful"); //Only succeeds and executes on desktop
                $('#uploadImageModal').modal('hide');
                $('#uploaded_image').html(data);
            }
        });
    })
});

我很困惑为什么这在移动设备上失败了。 我认为一个问题可能是我正在通过 Ajax 发送一个 blob,并且移动设备可能无法处理 blob 格式,但经过进一步审查后,我没有看到支持这一点的证据。 这就是为什么我想知道我在这里可能会遗漏什么。 作为旁注,我的表单与 Button 不在同一个位置,因为我的 Button 处于模式中。 由于我使用的是表单数据,因此我假设在实际表单中没有提交按钮不会导致问题,而且这在台式机和笔记本电脑设备上也不是问题。

这是 multipart/form-data 所以我需要更改 enctype。 这就是为什么我在某些设备上遇到问题的原因,自这篇文章以来,问题已得到解决。 在 ajax 请求中,我只需要添加:

enctype: 'mutipart/form-data',

这解决了这个问题。

When this happened, i discovered that the origin links e.g www.google.com and google.com, make it confusing for the browser. The browser sees it as two different host and don't know which of the links to trust. The way to solve it is to force all redirection to either one you would prefer. In my case i created a ".htaccess" file with this rules and walaaa my problem was solved. This also applies to cookies and sessions not working.


 

    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

暂无
暂无

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

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