出于某种原因,我无法从控制器获取post变量
AJAX / Javascript
function uploadImage(userActionPath,type)
{
if( (userActionPath == 'undefined') || (type == 'undefined')) {
console.error("no parameters for function uploadImage defined");
}
if((base64code == 'undefined') || (base64code == null))
{
console.error("please select an image");
}
var xml = ( window.XMLHttpRequest ) ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
alert(base64code); //<- shows the base64 code, so its there
var params = userActionPath+"?imagebase64="+base64code+"&type="+type;
xml.open("POST",userActionPath,true);
xml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xml.onreadystatechange = function()
{
if( xml.readyState === 4 && xml.status === 200 )
{
var serverResponse = JSON.parse(xml.responseText);
switch(serverResponse.f)
{
case 0:
console.log('love sosa'); //<- I get the response
break;
}
}
};
xml.send(params);
}
控制器
class LiveuploadController extends Controller
{
/**
* @Route("/LiveUpload",name="fileLiveUpload")
* @Template()
*/
public function indexAction(Request $request)
{
//I have tried these but 'imagebase64' returns null
//returns null
$value = $request->request->get('imagebase64');
//returns null
$value = $request->query->get('imagebase64');
//returns null
$value = $this->get('request')->request->get('imagebase64');
$response = array('f'=>0,'base64'=>$value);
return new Response(json_encode($response));
}
}
请求标头还显示正在发送变量。但是类型和imagebase64变量在控制器上都返回null
答案 0 :(得分:2)
问题在于您设置XmlHttpRequest的方式。您已将其设置为应该使用GET
,但是当您想要POST
时,它会有所不同。有关如何发送POST
请求的详细信息,请查看this question。它的快速和肮脏是:
var xml = ( window.XMLHttpRequest ) ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
var params = "imagebase64="+base64code+"&type="+type;
xml.open("POST", userActionPath, true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.setRequestHeader("Content-length", params.length);
xml.setRequestHeader("Connection", "close");
xml.onreadystatechange = function()
{
if( xml.readyState === 4 && xml.status === 200 )
{
var serverResponse = JSON.parse(xml.responseText);
switch(serverResponse.f)
{
case 0:
console.log('love sosa'); //<- I get the response
break;
}
}
};
xml.send(params);
在您的示例代码中,您将标头设置为期望JSON,但您的参数是urlencoded。设置正确的标题应该可以解决问题。
在你的控制器中,如果你使用的是POST
,那么你应该得到这样的请求变量:
// Use this for getting variables of POST requests
$value = $request->request->get('imagebase64');
// This is used for getting variables of GET requests
$value = $request->query->get('imagebase64');
答案 1 :(得分:1)
JS
中的这行代码:
xml.open("POST",userActionPath,true);
您实际上是在提供userActionPath
而不是params
变量。它应该是:
xml.open("POST",params,true);
至于控制器的代码,你应该使用:
$value = $request->query->get('imagebase64');
希望这会有所帮助......