如何从一个AJAX请求与PHP返回信息? [英] How to return information with PHP from an AJAX request?

查看:114
本文介绍了如何从一个AJAX请求与PHP返回信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习AJAX和从我的本地服务器上做我的第一个请求,只要求一个XML或HTML文件,没有什么太困难的。我用PHP现在的工作,我的理解是相当好,这不是比使用XML / HTML太多的不同。

I've been learning about AJAX and making my first requests from my local server, only requesting an XML or HTML file, nothing too difficult. I'm working with PHP now, and I understand it fairly well, it's not too much different than using the XML/HTML.

尽管经历教程我见过回到返回信息的JavaScript的几种不同的方式;我很好奇,是否有一个'正确'的方式,或者这样做的甚至是比较正确的方式。到目前为止,我所遇到的三种方法:

While going through tutorials I've seen a few different ways of returning information back to JavaScript; I am curious as to whether or not there is a 'right' way, or even a 'more correct' way of doing this. Thus far I have come across three methods:

someFile.php:

someFile.php:

<?php
$foo = $_GET['bar'];

// manipulate $foo

exit($foo); // method 1
echo $foo;  // method 2

// method 3:
?>

<div id='baz'>
    <p>
        Some output to be returned to JavaScript as the 'responseText'
        property of the AJAX request.
    </p>
    <p>
        <?php echo $foo ?>
    </p>
</div>

我只是不确定从服务器返回给浏览器返回信息的过程中。什么都被发回?凡是将显示,如果这是一个网页,人们实际上应该参观?感谢您的帮助!

I'm simply unsure of the process of returning information from the server back to the browser. What all gets sent back? Anything that would be displayed if this were a page that people were actually supposed to visit? Thanks for you help!

推荐答案

您需要看看PHP脚本,生成浏览器请求的HTML / JSON / XML文档的程序。在Ajax中,浏览器不一样的:它要求的文件一定URL。只是它可能只是一个片段,或JSON,你将融入使用JavaScript的网页。

You need to look at PHP scripts as programs that generates HTML / JSON / XML documents that the browser requested. In AJAX, the browser does just the same: it request the document for a certain URL. Only it might just be a fragment, or JSON that you will integrate into the page using JavaScript.

对于AJAX在一般情况下,这两种方法是比较正确的,尽管我还没有看到退出(...)的方法为止。无论生成一个文档工作。

As for AJAX in general, neither approach is more correct, even though I haven't seen the "exit(...)" approach so far. Whatever generates a document will work.

对于最佳实践,你可能最终需要从文件的生成单独的计算。但我猜你应该先获得基本的PHP,HTML,AJAX等更多的经验,当你写成为应用程序如此之大,你开始有困难找到你周围的code的方式,您可能希望看看MVC框架的PHP,这解决了分离计算(商业/模式逻辑)和生成文件(意见)的问题。我听到的Symfony是很受欢迎的一个。

Regarding best practices, you might eventually want to seperate your calculations from the generation of the documents. But I'd guess you should first gain more experience with basic PHP, HTML, AJAX, etc. When the applications you write become so big that you start to have difficulties to find your way around your code, you might want to look at MVC frameworks for PHP, which solve the problem of separating calculations (business / model logic) and document generation (views). I hear Symfony is a popular one.

这篇关于如何从一个AJAX请求与PHP返回信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆