注意:如果我从其他客户端Chrome扩展程序运行此API,则可以正常工作,否则我会收到以下错误...
由于以下错误,应用程序无法运行: 细节 键入:ErrorException 代码:8 消息:尝试获取非对象的属性 行:114
路线:
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/events','getEvents');
$app->get('/events/:year/:month', 'getMonth');
$app->get('/events/:year/:month/:day','getAllAfter');
$app->post('/events', 'addEvent');
$app->run();
这是我的功能:
function addEvent() {
$app = \Slim\Slim::getInstance();
$request = $app->request();
$body = $request->getBody();
$event = json_decode($body);
//Line 114
$submited_date = $submited_date = $event->{'date_submit'} .' '.$event->{'time_submit'};
$sql = "INSERT INTO events (edate, title, performers, address) VALUES (:edate, :title, :performers, :address)";
try {
$conx = getconx();
$stmt = $conx->prepare($sql);
$stmt->bindParam("edate", $submited_date);
$stmt->bindParam("title", $event->etitle);
$stmt->bindParam("performers", $event->performers);
$stmt->bindParam("address", $event->address);
$stmt->execute();
$event->id = $conx->lastInsertId();
$conx = null;
$result = array("status"=>"success","events"=>$event);
echo json_encode($result);
} catch(PDOException $e) {
$result = array("status"=>"error","message"=>'Exception: ' . $e->getMessage());
echo json_encode($result,JSON_PRETTY_PRINT);
}
}
这是json发送的:
{
"date":"24 March, 2014",
"date_submit":"2014-03-24",
"time":"4:00 PM",
"time_submit":"16:00:00",
"etitle":"Event Title",
"performers":"david",
"address":"Place"
}
jquery代码: 使用JSON.stringify()修复;发送请求前的数据
function addEvent(jsondat) {
console.log('addEvent');
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL,
dataType: "json",
data: JSON.stringify(jsondat); ,
success: function(data, textStatus, jqXHR){
alert(Event created successfully');
},
error: function(jqXHR, textStatus, errorThrown){
alert('addEvent error: ' + textStatus);
}
});
}
jQuery(document).on('ready', function() {
jQuery('form#myForm').bind('submit', function(event){
event.preventDefault();
var form = this;
var pson = ConvertFormToJSON(form);
//document.write(JSON.stringify(pson));
addEvent(pson);
});
});
答案 0 :(得分:2)
发现了问题,而且我的index.php中没有 这是在ajax请求中...... 这是通过使用JSON.stringify()到我的序列化数组修复的。
这就是为什么只是在其他客户端工作,因为那里的json发送正确... 感谢Matt提供的超薄框架支持 http://help.slimframework.com/discussions/problems/6789-not-able-to-handle-post-request