[英]Call php from javascript and return an array from php to Javascript function
I want to write a function in javascript which will call the Getfilename.php and Get the $filesArray that is return in javascript. 我想在javascript中编写一个函数,该函数将调用Getfilename.php并获取在javascript中返回的$ filesArray。
GetFilenme.php is another file and I am trying to access this from Config.html GetFilenme.php是另一个文件,我正在尝试从Config.html访问此文件。
PHP : Getfilename.php PHP的:Getfilename.php
<?php
$dir = 'uploads/';
$dir = $_REQUEST['dir'] ;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file)
{
if ($file!='.' && $file!='..' )
{
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'<br>';
$Counter = $Counter + 1;
}
}
return $filesArray;
?>
This is assuming you download and include the jQuery javascript library: 这是假设您下载并包含jQuery javascript库:
$(function() {
$.get('getfilename.php', { dir : 'path/to/dir' }, function(data) {
// you should now have a json encoded PHP array
$.each(data, function(key, val) {
alert('index ' + key + ' points to file ' + val);
});
}, 'json');
});
This should be your PHP (although very insecure): 这应该是您的PHP(尽管非常不安全):
<?php
$dir = $_REQUEST['dir'] ;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'';
$Counter++;
}
}
echo json_encode($filesArray);
?>
Use an asynchronous HTTP request in the JavaScript to load the output of the PHP script. 在JavaScript中使用异步HTTP请求来加载PHP脚本的输出。
For example, using the Prototype framework's Ajax.Request , say you have an HTML element with id="notice"
and you want to update that based on the script's output (a simple "true" or "false" string). 例如,使用Prototype框架的Ajax.Request ,假设您有一个
id="notice"
的HTML元素,并且您想根据脚本的输出(简单的“ true”或“ false”字符串)对其进行更新。
new Ajax.Request('/validate.php', {
method: 'get',
onSuccess: function(transport) {
var notice = $('notice');
if (transport.responseText == 'true')
notice.update('Validation successful');
else
notice.update('Validation failed');
}
});
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function CallSomePHP(username, password)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="myPhp.php";
url = url+"?username="+username+"&password="+password;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
alert(xmlhttp.responseText); // this will alert "true";
}
}
myphp.php myphp.php
<?
// Get the values of username and password
$username = $_GET['username'];
$password = $_GET['password'];
echo"true";
?>
You should try JQuery. 您应该尝试使用JQuery。 I send and receive from JS to PHP the following way, assuming this is the form.
我以下面的方式从JS到PHP发送和接收,假设这是表格。
<div id="form">
<input type="text" id="email" /><br />
<button id="submit">Submit</button>
</div>
<div id="response">
</div> <!-- load jquery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" > </script>
// put this in script type="text/javascript" tags
$(document).ready(function(){
var emailValue;
$("#submit").click(function(){
// when the user clicks the submit button
// get the value of email and put it in the variable we made above
emailValue=$("#email").val();
/* am going to send a post variable called "email"
* with the value of "emailValue" to a script called receiver.php
*/
$.post('receiver.php',{email:emailValue},function(e){
// "e" is variable that contains the echoed string
// check if it's true or false
if(e=="true")
alert ("valid email");
else
alert("invalid email");
});
});
});
$email=$_POST['email'];
// checkMail is a fictional function that returns a bool
$valid=checkMail($email);
if($valid)
{
// email is valid
echo "true";
}else{
// email is invalid
echo "false";
}
Note: if you are not sending data to the PHP script you should use $.get
instead of $.post
, it's a little bit faster. 注意:如果不向PHP脚本发送数据,则应使用
$.get
而不是$.post
,这会更快一些。
You can also use the JavaScript variable e
and load its contents in the response
division in your form like this 您还可以使用JavaScript变量
e
并将其内容以这种形式加载到response
分区中
$("#response").html(e);
This would accomplish the same thing as if you used JQuery's load()
function like Coder mentions below. 这将完成与使用JQuery的
load()
函数(如下面的Coder所述load()
一样的操作。
At the end, do this: 最后,执行以下操作:
print json_encode($filesArray);
and it will send back a json object, which Javascript can read easily. 它将返回一个JSON对象,该Javascript可以轻松读取。
If you're just using JavaScript, probably the simplest solution is to include that as a <script>
tag. 如果您仅使用JavaScript,则可能最简单的解决方案是将其作为
<script>
标记包括在内。
eg: 例如:
<script src="Getfilename.php" type="text/javascript"></script>
Then in your PHP, instead of: 然后在您的PHP中,而不是:
return $filesArray;
have it write some JavaScript. 让它编写一些JavaScript。
echo "var result = ".json_encode($filesArray).";";
Your $filesArray value will now be in your javascript as the variable result
. 您的$ filesArray值现在将作为变量
result
出现在您的javascript中。
<script>alert(result)</script>
The PHP should be stored on a remote server and called using a scripted HTTP request. PHP应该存储在远程服务器上,并使用脚本HTTP请求进行调用。 Read up on AJAX for details of how this works and how to perform such tasks.
阅读有关AJAX的详细信息,了解其工作原理以及如何执行此类任务。
You can't just do it in a browser as JavaScript has no PHP interpreter and neither do most browsers, and so can't just run a PHP file to get output. 您不能只在浏览器中执行此操作,因为JavaScript没有PHP解释器,大多数浏览器也没有,因此不能仅运行PHP文件来获取输出。
If your not using a javascript framework like jquery or prototype then you will have to create a XMLHttpRequest object yourself which the javascript framework would normally wrap up. 如果您没有使用jquery或prototype这样的javascript框架,则必须自己创建一个XMLHttpRequest对象,该对象通常会由javascript框架包装。 Something like the following:
类似于以下内容:
function GetHttpObject()
{
if (typeof XMLHttpRequest != 'undefined')
return new XMLHttpRequest();
try
{
return new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return false;
}
You can get it easily by ajax. 您可以通过Ajax轻松获得它。 Even you can use Jquery to post the value to php and get the ajax response within a single line of code like below.
甚至您也可以使用Jquery将值发布到php,并在如下一行代码中获得ajax响应。
p['value']=2;//some input value to be posted
$('#data').load('http://example.com/validator.php',p,function(str){} );
html: 的HTML:
<div id="data">
</div>
In this piece of code you are posting p['value'] as 2 to the validator.php and getting the response and load that value to data div in the same page. 在这段代码中,您将p ['value']作为2张贴到validator.php,并获得响应并将该值加载到同一页中的data div中。
In our php code //get the posted value into some $value and 在我们的PHP代码中//将发布的值转换为$ value并
if($value==2)
echo 'true I got 2'
else
echo 'I didnot got 2 You posted wrong value';
This will print true I got 2 in the div #data. 这将打印正确,我在div #data中得到了2。 This may not be your exact requirement but its very helpful.
这可能不是您的确切要求,但很有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.