Javascript value to PHP with Jquery

荒凉一梦 提交于 2019-12-24 08:38:37

问题


My javascript file:

var ms = 3000;
$.get("curl.php", { test: ms } );

My curl.php:

$ms = $_GET("test");
echo $ms;

Firefox firebug says:

Fatal error: Function name must be a string in C:\Users\Jansu\Documents\workspace\php\curl.php on line 2

what could be the problem?

Even better would be when the javascript and php code is in the same file, so I don't have to post/get anything. Just somehow pass javascript to php.


回答1:


You want [], not () (docs):

$ms = $_GET["test"];

Re your edit:

even better would be when the javascript and php code is in the same file, so i do not have to post/get anything. just somehow pass javascript to php

Even if they're in the same file, they're executed in completely different places. The JavaScript is executed on the client, the PHP is executed on the server. To get data from the client to the server, it has to be sent there. Ajax (the way you did it) is the primary way you do that without causing a full page refresh, so you're on the right track.




回答2:


You don't mention if you are sanitising your data separately, but the filter_input function is more secure than calling $_GET directly.

Also POST is generally considered better than GET for AJAX calls as it doesn't have the same string length limit, slightly more secure too.

$ms = filter_input(INPUT_POST, 'test', FILTER_SANITIZE_STRING);



回答3:


<script type="text/javascript">
 var ms = 9000;
function test()
{
    $.ajax({ url: "a.php",
         data: {"test":ms},
         type: 'get',
         success: function(output) {
                      $('#testing').html(output);
                  }
    });
}
test();
</script>
<?php
$ms = $_GET["test"];
echo "$ms";
?>
<div id="testing">
</div>

You can echo the output in any HTML element. Here i'm using div.



来源:https://stackoverflow.com/questions/5882442/javascript-value-to-php-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!