1
我正在嘗試使用slim框架,並且當我執行POST時輸入記錄時完全沒有任何操作。恐怕我將參數標識爲空,因爲如果我在數據庫中允許它,請輸入空記錄。
這是mi slim PHP。jQuery對Slim框架的AJAX調用PHP函數傳遞參數爲null
$app-> post("/banda/", function() use($app){
$nombre=$app->request->post("nombre");
try{
$connection = getConnection();
$dbh = $connection->prepare("INSERT INTO banda VALUES(null, ?)");
$dbh->bindParam(1, $nombre);
$dbh->execute();
$banda = $connection->lastInsertId();
$connection= null;
$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$app->response->body(json_encode($banda));
}catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
});
這是我的JS
var API_URI = "http://localhost/banda/";
function limpiar() {
$("#form-band input:first-child").val("");
}
function nombreBandaEsVacia() {
return ($("#form-band input:first-child").val().length == 0);
}
function getBandaJSON() {
return JSON.stringify({
nombre: getBandaNombre()
});
}
function getBandaNombre() {
return $("#form-band input:first-child").val();
}
$("#form-band input:last-child").on("click", function createBanda() {
if (nombreBandaEsVacia()){
alert("Oops! Completa el formulario!");
}else{
// 1.2 JSON.Stringify
var banda = getBandaJSON();
};
$.ajax({
type:'POST',
crossDomain: true,
url:API_URI,
data:banda,
dataType:"json",
beforeSend: function() {
console.log(banda);
},
success:function(response, banda) {
limpiar();
},
error:function(jqXHR, data, textStatus, errorThrown) {
console.log(data);
console.log(errorThrown);
console.log(jqXHR);
console.log(textStatus);
}
});
});
我的導航儀這樣說:
http://s2.subirimagenes.com/imagen/previo/thump_91447311.png
我很抱歉,我編輯我的文字 – JaviStinson 2014-11-03 17:39:24
@JaviStinson不要'stringify'它,只需返回對象,以便發送鍵值對而不是字符串。 – jeroen 2014-11-03 17:40:50
Ok @ jeroen解決了它。謝謝!! – JaviStinson 2014-11-03 17:47:28