无法获取AJAX的帖子值(纯Javascript) [英] Unable to get AJAX's post values (plain Javascript)

查看:106
本文介绍了无法获取AJAX的帖子值(纯Javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道此问题已在该论坛中得到解答(

I'm aware that this question was answered in this forum (Unable to get values in POST php web serivce), but both the question and the answer used jQuery and, in my case, I can't use it (no matter why)...

因此,我有一个Javascript文件,旨在制作画布的屏幕截图"(使用"toDataURL()"函数),并使用AJAX将其发送到PHP文件.由于要发送的数据非常长,因此我无法使用"GET"方法(AJAX返回414错误:"URL TOO LONG"),因此我需要使用"POST".

So, I have a Javascript file that is intended to make a canvas' "screen capture" (using the "toDataURL()" function) and send it to a PHP file using AJAX. As the data to be sent is really long, I can't use the "GET" method (AJAX returns a 414 error: "URL TOO LONG"), so I need to use "POST".

我已经遵循了普通Javascript 上的一些示例(由于每个人都使用jQuery!:P,所以很难找到它们),我的代码如下所示:

I've followed some examples on plain Javascript (which are by no means easy to find, because everyone uses jQuery! :P) and my code looks like this:

var dataURL = me.video.getScreenCanvas().toDataURL();

var req = false;
try{
req = new XMLHttpRequest();
} catch (e){
// IE
try{
    req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
    // try an older version
    try{
    req = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e){
    return false;
    }
}
}

req.onreadystatechange = function(){
    if(req .readyState == 4){
    if(req.status == 200)
    { 
        console.log("RESULT AJAX: "+req.responseText);
    }else{ 
        console.log("ERROR AJAX: returned status code "+req.status+" "+req.statusText); 
    }
    }
}

req.open("POST", "http://www.mywebpage.com/image_upload.php", true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("imgdata="+dataURL);

当尝试记录"dataURL"变量的内容时,它记录了一个大字符串,例如"image/png ... blablabla",因此我认为数据是按预期生成的.

When trying to log the content of the "dataURL" variable, it logs a large string like "image/png...blablabla", so I presume the data is generated as expected.

此刻,PHP文件仅尝试检索结果:

At this moment, the PHP file just tries to retrieve the result:

<?php

$imageData = '';

if(isset($_POST['imgdata']))
{
    echo "correct POST!";
    $imageData = $_POST['imgdata'];
}else if(isset($_GET['imgdata'])){
    echo "correct GET!";
    $imageData = $_GET['imgdata'];
}

echo "ImgData: ".$imageData;

if($imageData != '')
{
    $imageData = str_replace(' ','+',$imageData);
    $decodedData = base64_decode($imageData);

    if(file_put_contents('imatge1.jpeg', $decodedData) !== FALSE)
    {
        echo "Image has been successfully processed...?";
    }else{
        echo "Error trying to process the image...";
    }
}

?>

但是,PHP文件没有回显"POST"或"GET"消息,"ImgData"回显返回空,并且没有回显"success"或在处理图像时出错"消息...因此似乎PHP文件无法检索通过AJAX的"POST"方法传递的数据.

However, the PHP file doesn't echo the "POST" nor the "GET" messages, the "ImgData" echo returns empty and no "success" nor "error while processing image" message is echoed... So it seems that the PHP file is not able to retrieve the data passed by AJAX's "POST" method.

我做错了什么?我该如何仅使用纯Javascript (重要的是不要使用jQuery )来解决此问题?

What am I doing wrong? How could I solve this problem using just plain Javascript (it's important not to use jQuery)?

提前感谢您的时间和精力! :)

Thanks in advance for your time and effort! :)

推荐答案

我更改了您的JavaScript,并对其进行了测试,请尝试是否与您一起使用:

I changed your javascript, and tested this, please try if it work with you :

function create_XHR(){
    var XHR = null;
    if (window.XMLHttpRequest){
        XHR = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){
        try {
            XHR = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            XHR = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    else {
        alert("Your navigator is old to run objets XMLHTTPRequest...");
        XHR = false;
    }
    return XHR;
}


function ajax_post(page, data) {

    var XHR = create_XHR();
    XHR.open("POST", page, true);
    XHR.onreadystatechange = function() {
        if (XHR.readyState === 4 && (XHR.status === 200 || XHR.status === 0)) {
            console.log("Success Transaction");
        }
    };
    XHR.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    XHR.send(data);
}


//Running the code :
//==================
var dataURL = me.video.getScreenCanvas().toDataURL();
ajax_post("http://www.mywebpage.com/image_upload.php", {"imgdata":dataURL});


修改cors http: 在服务器PHP中,将其添加到页面"image_upload.php"的第一部分:


Modify the cors http : in the server PHP add this in first of your page "image_upload.php":

//Part added by ilyas :
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
//End of part.

这篇关于无法获取AJAX的帖子值(纯Javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆