很多人似乎在使用ajax传递参数时遇到问题。我查看了很多帖子,但没有一个答案对我有用。
我在Symfony工作。我试图通过ajax传递参数,以便我可以更新表数据,但即使javascript读取我的数据,我似乎无法在我的控制器中接收它。
Javascript功能是:
$('#form-save').click(function(){
$('#myModal').modal('hide');
var parent = $(this).parent().parent();
var target = parent.attr('target');
var title = $('#title-'+target);
var id = $('#form-info').attr('row');
var date = $('#date-'+target);
var dateTime = new Date(date.text());
var curr_date = ("0" + dateTime.getDate()).slice(-2);;
var curr_month = ("0" + (dateTime.getMonth() + 1)).slice(-2);
var curr_year = dateTime.getFullYear();
var from = $('#from-'+target);
var till = $('#till-'+target);
var description = $('#description-'+target);
//First Log
console.log(target + title.text() + date.text() + from.text() + till.text() +description.text() );
$.ajax({
type: "POST",
url: "{{ path('restaurant_my_events') }}",
data: {
action: 'update',
id: id,
title: title.text(),
date: curr_year + "-" + curr_month + "-" + curr_date ,
from: from.text(),
till: till.text(),
description: description.text()
},
dataType: "json",
success: function(response) {
//Second Log
console.log( response );
}
});
对于调试我在控制台上记录两次,第一个日志的输出是:
0 hello world 06-14-2014 12:0612:06 description 2
这确认所有输入元素都匹配,读取数据时没有错误,第二个日志的输出只是为了验证我的控制器是否收到了我的参数。
控制器功能是:
public function myEventsAction(Request $request){
$restoID = 2;
$repository = $this->getDoctrine()->getRepository('LesDataBundle:Party');
$events = $repository->findByRestoId( $restoID );
if ($request->isXMLHttpRequest()) {
$status = false;
$action = $request->get('action');
$partyID = $request->get('id');
if($action == 'delete'){
//Delete function
}else if($action == 'update'){
//Update function
}
$test = $action ." + ". $partyID ." + ". $request->get('title') ." + " . $request->get('date') ." + " .
$request->get('from') ." + " . $request->get('till') ." + " . $request->get('description');
return new JsonResponse(array(
'id' => $partyID , 'request' => $request , 'test' => $test));
}
return $this->render("LesRestaurantBundle:Admin:Events/myEvents.html.twig",
array( 'events' => $events ));
}
第二次记录的输出是:
Object {id: "2", request: Object, test: "update + 2 + + NaN-aN-aN + + + "}
我只收到参数ID。为什么呢?
答案 0 :(得分:0)
在通过AJAX发送之前,尝试使用encodeURIComponent()
转换字符串。