很多人似乎在使用 ajax 传递参数时遇到问题。我看了很多这样的帖子,但没有一个答案对我有用。
我在 Symfony 工作。我试图通过 ajax 传递参数,以便我可以更新表数据,但即使 javascript 读取我的数据,我似乎无法在我的 Controller 中接收它。
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
这确认了所有输入元素都匹配,读取数据没有错误,第二个日志的输出只是为了验证我的 Controller 是否收到了我的参数。
Controller 功能是:
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。为什么?
最佳答案
在通过 AJAX 发送之前,尝试使用 encodeURIComponent()
转换字符串。
关于javascript - 在 Ajax 中将字符串作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24219028/