Symfony 2에 JSON 개체 게시
Symfony 2를 사용하여 프로젝트를 진행하고 있으며, JSON 데이터를 주고받는 모든 데이터베이스 서비스를 처리하기 위한 번들을 구축했습니다.
문제/질문:
JSON 오브젝트를 똑바로 올릴 수 있나요?현재 오브젝트에 이름을 붙임으로써 내 Ajax 호출에 대한 일반 폼 포스트를 스푸핑하고 있습니다.
json={"key":"value"}
이름을 지정하지 않으면 Symfony 요청 개체에서 데이터를 가져올 수 없습니다.$JSON = $request->request->get('json');
하나의 서비스 번들을 사용하여 AJAX 콜 또는 일반 Symfony 형식을 모두 처리할 수 있도록 하고 싶습니다.현재 제출된 Symfony 폼을 사용하여 데이터를 취득한 후 JSON_ENCODE를 사용하여 요청 데이터를 기다리는 서비스 컨트롤러에 데이터를 게시하는 방법을 알 수 없습니다.
요약:
Symfony가 폼이 아닌 JSON 포스트 오브젝트를 받아들이기를 원합니다.
Request/Response를 사용하여 컨트롤러 간에 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
}
}
지금이다$params
JSON 데이터가 가득 찬 배열이 됩니다.를 삭제합니다.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.disc.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, 그게 네가 원했던 것 같아:)
편집 폼을 시뮬레이션하지 않고 송신하려면 jQuery.ajax()를 사용합니다.다음은 페이지 새로 고침을 트리거하지 않는 위와 같은 정신의 예입니다.
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
'programing' 카테고리의 다른 글
Argparse:'--help'에 기본값을 포함하는 방법? (0) | 2022.10.03 |
---|---|
MySQL 5.0 인덱스 - 고유 대 고유하지 않음 (0) | 2022.10.03 |
테이블의 기본 키를 얻는 방법 (0) | 2022.10.03 |
OutputStream에서 InputStream을 생성하는 가장 효율적인 방법 (0) | 2022.10.03 |
명령줄을 통해 JVM args를 Maven에 전달하는 방법이 있습니까? (0) | 2022.10.03 |