Javascript den php Çağrı ve php Javascript işlevin bir dizi döndürür

10 Cevap php

Ben Getfilename.php aramak ve javascript içinde dönüş $ filesArray alın olacak javascript bir fonksiyon yazmak istiyorum.

GetFilenme.php başka bir dosya ve ben config.html bu erişmeye çalışıyorum

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;
?>

10 Cevap

Bu indirmek ve jQuery javascript kütüphanesi şunlardır üstleniyor:

$(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');
});

Bu (çok güvensiz rağmen) PHP olmalıdır:

<?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); 
?>

PHP script çıktı yüklemek için JavaScript uyumsuz bir HTTP isteği kullanın.

Örneğin "Prototype çatınızdaki Ajax.Request, sen id="notice" ile bir HTML öğesi var demek kullanarak ve basit bir (betiğin çıktıya dayalı olduğunu güncellemek istiyorum true "veya" false "dizesi).

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

<?
  // Get the values of username and password
  $username = $_GET['username'];
  $password = $_GET['password'];
  echo"true";
?>

Sen JQuery denemelisiniz. Ben göndermek ve bu formu olduğunu varsayarak, aşağıdaki şekilde PHP JS alırsınız.

<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");
    });

  });

});

receiver.php

$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: Eğer $.get yerine $.post, bu biraz daha hızlı kullanımı gereken PHP komut dosyası veri gönderme değilse.

Ayrıca JavaScript değişkeni e kullanmak ve bu gibi formda response bölümü içeriğini yükleyebilirsiniz

$("#response").html(e);

Eğer Coder gibi JQuery'nın load() fonksiyonu aşağıda bahseder kullanıldığı gibi, bu aynı şeyi başarmak istiyorum.

Bu sayfayı kontrol edin http://ajaxpatterns.org/XMLHttpRequest_Call

Tüm site de bir göz değer.

Sonunda, bu do:

print json_encode($filesArray);

ve Javascript kolayca okuyabilir hangi bir json nesnesi geri gönderecektir.

Sadece JavaScript kullanarak yapıyorsanız, muhtemelen basit çözüm bir <script> etiketi olarak bu eklemektir.

örneğin:

<script src="Getfilename.php" type="text/javascript"></script>

Sonra PHP, yerine:

return $filesArray;

bazı JavaScript yazmak var.

echo "var result = ".json_encode($filesArray).";";

Sizin $ filesArray değeri artık değişken olarak javascript olacak result.

<script>alert(result)</script>

PHP bir uzak sunucuda depolanan ve bir komut dosyası HTTP isteği kullanarak aranmalıdır. Bu nasıl çalıştığını ayrıntıları ve ne gibi görevleri gerçekleştirmek için AJAX kadar okuyun.

JavaScript hayır PHP yorumlayıcısı vardır gibi sadece bir tarayıcıda bunu yapamaz ve ne en tarayıcılarını yapmak, ve bu yüzden sadece çıktısını almak için bir PHP dosyasını çalıştıramazsınız.

Sen ajax kolayca alabilirsiniz. Hatta php için değer gönderebilir ve aşağıdaki gibi bir kod tek bir satır içinde ajax yanıt almak için jQuery kullanabilirsiniz.

p['value']=2;//some input value to be posted
$('#data').load('http://example.com/validator.php',p,function(str){}    );

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.

In our php code //get the posted value into some $value and

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. This may not be your exact requirement but its very helpful.

click here for best example

Ben sorun var ama linke bana yukarıda javascript php dizi dönüştürmek için yardımcı