1

我的 Cordova 应用程序中有一个表格:

<form id='transport' method='POST' action='' enctype='application/json'>
    <input type='hidden' id='data' name='data' value='' />
</form>

我发送到服务器(纯js):

postdata = '{';
postdata += '"first_name": "Jon",';
postdata += '"last_name": "Snow"';
postdata += '}';

document.getElementById('data').value = postdata;
document.getElementById('transport').action = 'http://testserver.com/add_user/';
document.getElementById('transport').submit();

但是在服务器上接收到数据变量时为空。

在服务器上我使用Codeigniter

在 Web 场景中完美运行,为什么不在 Cordova 中呢?我知道不存在跨域问题,并且我已经允许 config.xml 中的所有域(*)。

谢谢。

4

2 回答 2

1

固定的!只需删除URL 末尾的斜杠(/)。

这是因为 Codeigniter - 带有这个斜线 - 期待另一个参数(由于其基于 url 的性质),如果没有,控制器内的所有变量(例如 POST 数据)都是空的。

所以这:

postdata = '{';
postdata += '"first_name": "Jon",';
postdata += '"last_name": "Snow"';
postdata += '}';

document.getElementById('data').value = postdata;
document.getElementById('transport').action = 'http://testserver.com/add_user';
document.getElementById('transport').submit();

这是正确的。

于 2014-05-15T19:11:19.163 回答
0

您可以使用xmlhttp使用纯 JS 来实现这一点。

这一个省略了data变量的包装,所以你得到first_namelast_name作为自己的参数。

function addUser(first_name, last_name){
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            alert("successfully added user");
            console.log(xmlhttp.response);//this is the response from the server
        }
    }

    params = "first_name=" + first_name + "&last_name=" + last_name;

    xmlhttp.open("POST", "http://testserver.com/add_user",true);

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");

    xmlhttp.send(params);
}

您还可以像这样以 JSON 格式发送数据:

function addUser(first_name, last_name){
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            alert("successfully added user");
            console.log(xmlhttp.response);//this is the response from the server
        }
    }
    xmlhttp.open("POST", "http://testserver.com/add_user",true);

    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    //Not sure if you need the Content-length here or not. 

    xmlhttp.send(JSON.stringify({"data"=>{"first_name"=>first_name, "last_name" => last_name}}));
}

我发现这种方法比在不需要时使用不可见的形式更干净。

于 2014-12-14T19:57:40.903 回答