使用PHP的jQuery $ .ajax()

我正在尝试使用jQuery $ .ajax()但我遇到了一些困难。

这是我要用于POST的文本框字段:

 

这是代码:

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

现在这是file.php:

  

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

您只需打印/回显“返回”值即可。

file.php

  

然后在你的JS中:

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

作为旁注。 您的脚本看起来像是接受任何URL并获取它。 有可能滥用这样的脚本。 确保你知道这一点。

如果要返回一些变量/字段,最好的方法是回显JSON字符串。 这是一个小例子:

PHP代码:

  

JS代码:

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