将数据从knockout发送到php

时间:2016-08-16 14:49:52

标签: javascript php knockout.js

我创建了一个登录功能

self.login = function() {
    var credentials = {
        email: self.email(),
        pass: self.pass()
    }
    var data = ko.toJS(credentials);
    $.ajax({
        url: 'client/scripts/pages/login/login.php',
        type: 'post',
        data: {data: data},
        contentType: 'application/json',
        success: function (result) {
            alert(result);
        }
    });
}

这将在提交表单时向php文件发送请求。 这是login.php代码,

$data = json_decode($_POST['data']);
return $data['email'];

执行此操作时,结果为Undefined index:data

我尝试过JSON.strignify,但它无效。如何在php中获取用户的电子邮件?

1 个答案:

答案 0 :(得分:0)

我使用以下代码:

客户端(JS):

$.ajax((<any>{
    type: "POST",
    async: async,
    url: dataServiceBaseUrl + "request.php", //
    data: {
        "jsonrpc": "2.0",
        "method": method,
        "dbname": dbName,
        "params": JSON.stringify(params)
    },
    success: function(data) {
        var obj = JSON.parse(data);
    },
    error: function() {
    }
}));

服务器端(PHP):

function process_request() {
    $dbname = $_POST["dbname"];
    $method = $_POST["method"];
    $params = json_decode($_POST["params"], true);
    $result = call_user_func_array("methods::" .  $method, $params);
    return json_encode(array("jsonrpc" => "2.0", "result" => $result, "error" => null, "usename"=>$usename));
}

当然,

var data = ko.toJS(credentials);

是获取可序列化数据的必要条件。