Symfony 2에 JSON 객체 게시
저는 Symfony 2를 사용하여 프로젝트를 진행하고 있으며 JSON 데이터를 앞뒤로 전달하는 모든 데이터베이스 서비스를 처리하는 번들을 구축했습니다.
내 문제 / 질문 :
곧바로 JSON 객체를 게시 할 수 있습니까? 현재는 이름을 지정
json={"key":"value"}하지 않으면 객체에 이름을 지정하여 ajax 호출에 대한 일반 양식 게시물을 스푸핑하고 있습니다. Symfony 요청 객체에서 데이터를 가져올 수없는 것 같습니다.$JSON = $request->request->get('json');하나의 서비스 번들을 사용하여 AJAX 호출 또는 일반 Symfony 형식에서 오는 두 데이터를 모두 처리 할 수 있기를 원합니다. 현재 제출 된 Symfony 양식을 가져 와서 데이터를 얻은 다음 JSON_ENCODE를 사용하여 요청 데이터를 예상하는 서비스 컨트롤러에 데이터를 게시하는 방법을 알아낼 수 없습니다.
요약하면 :
Symfony가 양식이 아닌 JSON 게시 객체를 수락하기를 원합니다.
요청 / 응답을 사용하여 컨트롤러간에 JSON 개체를 전달하고 싶습니다.
내가이 모든 일에 대해 잘못 생각한다면, 그렇게 말 해주세요!
요청 본문에서 표준 JSON으로 전송 된 컨트롤러의 데이터를 검색하려는 경우 다음과 유사한 작업을 수행 할 수 있습니다.
public function yourAction()
{
$params = array();
$content = $this->get("request")->getContent();
if (!empty($content))
{
$params = json_decode($content, true); // 2nd param to get as array
}
}
이제 $paramsJSON 데이터로 가득 찬 배열이됩니다. 개체 를 가져 오려면 호출 true에서 매개 변수 값을 제거하십시오 .json_decode()stdClass
콘텐츠를 배열로 가져 오는 방법을 작성했습니다.
protected function getContentAsArray(Request $request){
$content = $request->getContent();
if(empty($content)){
throw new BadRequestHttpException("Content is empty");
}
if(!Validator::isValidJsonString($content)){
throw new BadRequestHttpException("Content is not a valid json");
}
return new ArrayCollection(json_decode($content, true));
}
그리고이 방법을 아래와 같이 사용합니다.
$content = $this->getContentAsArray($request);
$category = new Category();
$category->setTitle($content->get('title'));
$category->setMetaTitle($content->get('meta_title'));
페이지의 javascript :
function submitPostForm(url, data) {
var form = document.createElement("form");
form.action = url;
form.method = 'POST';
form.style.display = 'none';
//if (typeof data === 'object') {}
for (var attr in data) {
var param = document.createElement("input");
param.name = attr;
param.value = data[attr];
param.type = 'hidden';
form.appendChild(param);
}
document.body.appendChild(form);
form.submit();
}
이벤트 후 (예 : "제출"클릭) :
// products is now filled with a json array
var products = jQuery('#spreadSheetWidget').spreadsheet('getProducts');
var postData = {
'action': action,
'products': products
}
submitPostForm(jQuery('#submitURLcreateorder').val(), postData);
컨트롤러에서 :
/**
* @Route("/varelager/bestilling", name="_varelager_bestilling")
* @Template()
*/
public function bestillingAction(Request $request) {
$products = $request->request->get('products', null); // json-string
$action = $request->request->get('action', null);
return $this->render(
'VarelagerBundle:Varelager:bestilling.html.twig',
array(
'postAction' => $action,
'products' => $products
)
);
}
템플릿에서 (제 경우에는 bestilling.html.twig) :
{% block resources %}
{{ parent() }}
<script type="text/javascript">
jQuery(function(){
//jQuery('#placeDateWidget').placedate();
{% autoescape false %}
{% if products %}
jQuery('#spreadSheetWidget').spreadsheet({
enable_listitem_amount: 1,
products: {{products}}
});
jQuery('#spreadSheetWidget').spreadsheet('sumQuantities');
{% endif %}
{% endautoescape %}
});
</script>
{% endblock %}
Alrite, 나는 그것이 당신이 원했던 것이라고 생각합니다 :)
EDIT To send something without simulating a form you can use jQuery.ajax(). Here is an example in the same spirit as above which will not trigger a page refresh.
jQuery.ajax({
url: jQuery('#submitURLsaveorder').val(),
data: postData,
success: function(returnedData, textStatus, jqXHR ){
jQuery('#spreadSheetWidget').spreadsheet('clear');
window.alert("Bestillingen ble lagret");
// consume returnedData here
},
error: jQuery.varelager.ajaxError, // a method
dataType: 'text',
type: 'POST'
});
참고URL : https://stackoverflow.com/questions/9522029/posting-json-objects-to-symfony-2
'program story' 카테고리의 다른 글
| 조각 셰이더에 값 목록 전달 (0) | 2020.11.04 |
|---|---|
| TLD는 얼마나 오래 걸릴 수 있습니까? (0) | 2020.11.04 |
| $ http는 요청에서 쿠키를 보내지 않습니다. (0) | 2020.11.04 |
| Windows에서 Ubuntu 하위 시스템으로 파일 복사 (0) | 2020.11.04 |
| ButtonGroup에서 어떤 JRadioButton이 선택되었는지 어떻게 알 수 있습니까? (0) | 2020.11.04 |