我们需要什么?
为了简单起见,假设您需要在用户输入“敲门”时下一个字段填充“谁在那里”。
假设第一个字段(用户将填写)的 id 为 #input_filled_by_user,另一个字段的 id 为 #input_filled_with_php。
我们如何解决这个问题?
只要用户在脚本执行后会打字,我们就需要告诉我们他用“knock knock”(即 jQuery)写的特定单词,并将其发送到控制器(a REST API 的花哨名称)。
然后在控制器中我们处理并返回结果,并使用 jQuery(再次)将结果输出给用户。
代码
首先我们需要一个路由器:
my_door_keeper_router:
pattern: /request/{string}
defaults: { _controller: AcmeDemoBundle:door:keeper, _format: ~ }
requirements:
_method: GET
id: "\d+"
这里是动作控制器:
public function keeperAction($string)
{
if ($string == 'knock knock') {
echo "hello"; // please dont do it with echo use symfony way , i just dont have enough time
}
return;
}
现在使用 jQuery:
$('#input_filled_by_user').change(
function(){
$.get('/request', { string: $(this).val() } ,function(data) {
$('#input_filled_with_php').val(data);
alert('Load was performed.');
});
}
)
就是这样。希望这是有道理的(请深入挖掘,我试图以虚拟的方式解释它,我提到的一些事情是正确的,但无论您现在尝试做什么,都可以这样做)。