我试图使用cakephp中的ajax从数据表中获取数据。我发送了一个名为的数据,并希望获取所有记录。这就是我尝试的方式:
ajax:
$("#Designation").click(function(){
alert($("#Designation").val());
var data = {
"Designation": $("#Designation").val()
}
$.ajax({
type:"POST",
dataType: "JSON",
url: '<?php echo Router::url(array('controller'=>'DynamicForm','action'=>'getbulkoptions')); ?>',
data:data,
success:function(data){
alert("success");
console.log(data);
if(data.fieldid=="0"){
//MyNotif.Show(data.message,"warning");
alert("Field Exists");
}else{
$("#mymodal").modal('hide');
//MyNotif.Show(data.message,"success");
//window.location.reload();
alert("Bulk List");
}
},
error:function(XMLHttpRequest, textStatus, errorThrown){
console.log(XMLHttpRequest.responseText);
}
});
});
这是我尝试与数据库通信的方式:
DynamicFormController:
<?php
namespace App\Controller;
session_start();
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
class DynamicFormController extends AppController {
public function getbulkoptions(){
$optionvalue = $this->request->data('Designation');
$designation = TableRegistry::get ('Field');
$result = $designation->getbulkoptions($optionvalue);
echo json_encode($result);
}
}
?>
FieldTable:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Datasource\ConnectionManager;
class FieldTable extends Table {
var $name = 'FieldTable';
public function getbulkoptions($designation){
$conn = ConnectionManager::get('default');
$stmt = $conn->prepare( "CALL proc_getbulkoptionslist (:tid)");
$stmt->bindValue( ':tid', $designation);
$stmt->execute ();
return $stmt->fetchAll ('obj');
}
}
问题是,我得到了适当的回应。我得到了我想要的数据,但是数据正在ajax的错误函数中打印出来。我希望它成为成功的功能。我不知道上面的代码有什么问题。当我试图打印错误时,我得到了这个:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 364 of the JSON data
Stack trace:
n.parseJSON@http://localhost/payrollengine/js/jquery.js:4:16508
Wb@http://localhost/payrollengine/js/jquery.js:4:18828
y@http://localhost/payrollengine/js/jquery.js:4:22274
.send/c@http://localhost/payrollengine/js/jquery.js:4:26750
我在错误功能中尝试了这个并尝试打印出来,我得到了这个回复:
error:function(XMLHttpRequest, textStatus, errorThrown){
console.log(XMLHttpRequest.responseText);
}
response:
[{"fieldvalueid":"1","value":"Manager"},{"fieldvalueid":"2","value":"Project Manager"},{"fieldvalueid":"3","value":"Software Engineer"},{"fieldvalueid":"4","value":"Senior Software Engineer"},{"fieldvalueid":"5","value":"Associate Software Engineer"},{"fieldvalueid":"28","value":"sample"},{"fieldvalueid":"29","value":"azhagu"},{"fieldvalueid":"37","value":"t"}]null
我不知道代码有什么问题。有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
将json标头添加到控制器功能中:
header('Content-Type: application/json');
echo json_encode($result);
尝试从db
返回一个关联数组->fetchAll('assoc');