如何在PHP代码中返回变量?

我正在尝试使用jQuery$.ajax(),但我面临一些困难。下面是我想在POST中使用的TextBox字段:

<input name="url" class="url" type="text" >

代码如下:

$.ajax({
        type: "post",
        url: "file.php",
        data: $(this).serialize(),
        success: function(data) { ...............

下面是file.php:

<?php
if( $_REQUEST['url'] )
{

   $url = $_REQUEST['url'];
   $url = file_get_contents($url);  
   // I would need now to return something here but not sure how??!!
}
?>

现在,我的问题是,如何在这个PHP代码中返回变量并在上面的代码中使用它们,我的意思是$.ajax()的成功部分?另外,如果我想对$url变量执行一些额外的操作,如何执行呢?如何归还?

You just print/echo your 'return' value.

file.php

<?php
if( $_REQUEST['url'] )
{

   $url = $_REQUEST['url'];
   $url = file_get_contents($url);  
   // I would need now to return something here but not sure how??!!
   echo "something";
}
?>

Then in your JS:

$.ajax({
    type: "post",
    url: "file.php",
    data: $(this).serialize(),
    success: function(data) {
        console.log(data); // "something"
    }
});

As a side note. Your script looks like it accepts any URL and fetches it. It is possible to abuse scripts like that. Make sure you are aware that.

If you want to return some variables/fields, the best way would be to echo a JSON string. Here is a small example:

PHP Code:

<?php
if( $_REQUEST['url'] )
{

   $url = $_REQUEST['url'];
   $url = file_get_contents($url);  

   $result['var1'] = 'something';
   $result['var2'] = 500;

   echo json_encode($result);
}
?>

JS Code:

$.ajax({
    type: "post",
    url: "file.php",
    data: $(this).serialize(),
    dataType: 'json', // maybe not needed? I do not know if jQuery autodetects it
    success: function(data) {
        // here you can use data.var1 and data.var2 to read the fields
    }
});