Mat*_*tte 4 javascript php ajax jquery
所以当涉及到javascript和php时,我仍然是一个新手.我有这个问题:
从javascript,我使用条形码阅读器扫描包的条形码.我使用ajax将它发送到一个PHP文件,它构建一个对象,并需要将它返回到我的javascript代码.
我这样做:
function LoadPackage(ScannedCode) {
var res;
console.time("Load package " + ScannedCode);
$.ajax({
type: "POST",
url: "ajax/3gmodule_inventory_ajax/getPackage.php",
data: "packageSerial=" + ScannedCode,
cache: false,
async: false //inline operation, cannot keep processing during the execution of the AJAX
}).success(function(result) {
res = $.parseJSON(result);
});
console.timeEnd("Load package " + ScannedCode);
return res;
}
Run Code Online (Sandbox Code Playgroud)
php文件:
<?php
include_once "../../init.php";
$packageSerial = $_POST["packageSerial"];
$package = tbProductPackage::getInstanceByPackageSerial($packageSerial, $db);
return json_encode($package);
// edit: first part of the problem was here, I was supposed to ECHO here. not RETURN.
?>
Run Code Online (Sandbox Code Playgroud)
我100%确定我的对象是否正确构建.我确实做了我的$ package对象的var_dump,一切都很好.然而,当试图将它恢复到javascript时,我尝试了一堆不同的东西,没有任何作用.
$ .parseJSON(结果); 声明似乎给了我这个错误:
Uncaught SyntaxError: Unexpected end of JSON input
Run Code Online (Sandbox Code Playgroud)
我也尝试使用serialize(),但是我收到一条错误消息:
Uncaught exception 'PDOException' with message 'You cannot serialize or unserialize PDO instances'
Run Code Online (Sandbox Code Playgroud)
基本上,我的数据库在我的对象中,我猜我无法序列化它...
我在这做错了什么?
谢谢
在getPackage.php页面中:
echo json_encode($package);
Run Code Online (Sandbox Code Playgroud)
不使用 return
在Jquery应该是:
data: {packageSerial:ScannedCode},
Run Code Online (Sandbox Code Playgroud)
成功后不需要$.parseJSON(因为getPackage.php已经检索json encode
所以,应该是:
}).success(function(result) {
res = result
});
Run Code Online (Sandbox Code Playgroud)
也加了dataType: 'json',之后data: {packageSerial:ScannedCode},
所以,最终修正代码是:
Jquery:
function LoadPackage(ScannedCode) {
var res;
console.time("Load package " + ScannedCode);
$.ajax({
context: this,
type: "POST",
url: "ajax/3gmodule_inventory_ajax/getPackage.php",
data: {packageSerial:ScannedCode},
dataType: 'json',
}).success(function(result) {
res = result;
});
console.timeEnd("Load package " + ScannedCode);
return res;
}
Run Code Online (Sandbox Code Playgroud)
PHP:
<?php
include_once "../../init.php";
$packageSerial = $_POST["packageSerial"];
$package = tbProductPackage::getInstanceByPackageSerial($packageSerial, $db);
echo json_encode($package);
?>
Run Code Online (Sandbox Code Playgroud)