一直在兜圈子,试图让AJAX调用PHP服务器发生。 比几个小时前更近。 仍然不知道如何以任何意义访问 PHP 中的 $_POST 数据。
我的阿贾克斯出局
var __private_api = function() {
// workhorse. EVERY call to our server REST API comes through
// this interface. NO exceptions. We will NOT have an interface per
// form or per MODEL as is a common case. Makes no sense having an API really.
// Might as well just code willy7-nilly.
var packed = JSON.stringify(packet);
console.log(packed);
jqxhr = $.ajax({
method: "POST", // ALL API calls are POST
url: "oop/server.php/", // API code
dataType: "json", // JSON back at us please
//contentType: "application/json", // HEADER. IMPORTANT!
data: {"packed":packed} // form data + security packet
}).fail(function(msg) { // error is depreciated. WHY? Dunno...
alert("Database Communication failure"); // this is a HARD failure sent to
console.log(JSON.stringify(msg)); // us by the comms stack, authentication, or OS
}).done(function(data) { // AJaX worked, deal with the resultant packet
__private_callback(data); // in our custom callback. success() has been
}); // depreciated, replaced by bone(). Why???
}
这到了PHP,因为我可以这样做
$this->database->log_config->trace(json_encode($_POST));
$this->crud = 'EXEC';
$SQL = "SELECT * from patients limit 2";
switch($this->crud) {
case 'EXEC': // before we drop into CRUDDiness, handle
$this->database->execute($SQL); // well? This eithe dies or comes back
// it CAN come back with an empty SET
// that is an SEP.
$db_result = $this->database->fetch_all(); // retrieve tuples from the CURSOR
//$this->response['data'] = $db_result->get_stack(); // and shove in the parcel to go back to the CLIENT API
$this->response['data'] = json_decode(json_encode($_POST),true); // and shove in the parcel to go back to the CLIENT API
break;
这使它回到我的客户端代码,并且来自PHP代码的跟踪如下所示。
{"packed":" {'"type'":'"USER'",'"method'":'"LOGIN'",'"email'":'"root'",'"pw'":'"S0lari s7.1'",'"remember'":'"false'"}"}
所以东西似乎正在克服巨大的鸿沟。 如何在我的PHP代码中测试"type"的值以查看它是否为"USER"? 我一直在编码和解码,但似乎没有得到它!
干杯马克。
$_POST['packed'] 的值是一个 JSON 字符串。 为了检查type
的值,您首先需要使用 json_decode()
将 JSON 解码为本机 PHP stdClass 对象。
$packed = array_key_exists('packed', $_POST) ?
json_decode($_POST['packed']) :
null;
if ($packed && $packed->type === 'USER') {
// do stuff
}
在这里,我首先确保"packed"存在于$_POST
数组中。 如果是这样,我通过 json_decode()
传递它,否则返回 null。 如果 $_POST['packed'] 的值由于某种原因不是有效的 JSON,它也将返回 null。
接下来,我检查$packed
是否真实,$packed->type
等于"用户"。