在PHP中访问JS函数中的局部变量值


accessing local var value from JS function in PHP

在搜索互联网后,甚至在这里5个小时,我仍然停留在获取函数中局部变量的值并将其发送到PHP。

我试过不同的语法,但没有一个似乎是工作。下面的代码,从PHP中获取一个输入字段,并为其赋值(在将该值发送回PHP时遇到问题)

$(document).ready(function() {  
//select all the a tag with name equal to modal
$('form[name=modal]').click(function(e) {
    //Cancel the link behavior
    e.preventDefault();
    //Dont go until value is not 7
    console.log('i am Now waiting for input');
    var s = $('#serial').val();
    console.log('searching for ' + s);
    while(s.length != 7) return;

    //When code value reaches 7
    var code = $('#serial').val();
    console.log('Value is reached ' + s);
  });
});
在PHP中

echo "<script>document.write(code);</script>";
Uncaught ReferenceError: code is not defined

请帮

当$('#serial')是你的输入字段时,你应该在javascript中这样做。

$.ajax({'url':'your_php_file_url', 'type':'post', 'data':{'str':$('#serial').val()}}).done(function(data){
console.log(data.code);
});

在php中

$output = Array('code' => 'not set');
if (isset($_POST['str']))
{
//do your search and assigne value to output
$output['code'] = 'some value';
}
echo json_encode($output);

简而言之-您通过ajax将搜索字符串发送到php并进行搜索。然后将其作为json回显,然后ajax将其作为对象读取,您可以使用您想要的值

好吧,我几乎测试了所有可能的解决方案,但都是徒劳的…所以我离开并尝试使用一些正常的方法,而不是javascript。谢谢大家的回答。