如何调用从HTML或JavaScript的PHP文件 [英] How to call a PHP file from HTML or Javascript

查看:127
本文介绍了如何调用从HTML或JavaScript的PHP文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,很长一段时间,现在我无法找到任何地方,回答这个看似基本的问题。我不在乎,如果页面重新加载或立即显示结果;我只是想有一个按钮,在我的网站做一个PHP文件运行。而已。而且我发现,所有的网站要么告诉你如何在你的HTML直接运行PHP code或告诉你使用AJAX。我会用ajax如果事实证明是必要的,但有一段时间之前,阿贾克斯存在的PHP使用了,所以我觉得有一个简单的方法。如果我可以写在HTML里面就好了,为什么我不能只是引用文件,它在那里,或做一个简单的呼吁,它在Javascript中的code?

如果它变成了Ajax是唯一的出路,我该怎么需要了解它来调用一个PHP文件,该文件将创建一个按钮preSS的文本文件?我做一个简单的博客网站为我自己和我已经得到了code的网站和JavaScript的,可以采取我写了 textarea的帖子和立即显示出来。我只是想将其链接到一个PHP文件,该文件将在服务器上创建永久的博客文章,这样,当我重新加载页面,后仍然存在。

感谢您抽出时间来阅读和回答。

解决方案

如何使一个按钮调用PHP?

  

我不在乎,如果页面重新加载或立即显示结果;

大家好!

注意的:如果你不想刷新页面看到?的好......但我怎么使用Ajax反正的文章

  

我只是想在我的网站上的一个按钮使一个PHP文件中运行。

这可以用同一个按钮的形式来进行:

 <形式的行动=>
  <输入类型=提交值=我的按钮/>
< /形式GT;
 

  

就是这样。

pretty的多。另请注意,有一些情况下AJAX是真的要走的路。

这取决于你想要什么。概括地说,你只有当你想避免realoading页面需要AJAX。不过你说你不关心这一点。


为什么我不能直接从JavaScript调用PHP?

  

如果我可以写在HTML里面就好了,为什么我不能只是引用文件,它在那里,或做一个简单的呼吁,它在Javascript中的code?

由于PHP的code不是在 HTML就好了。这是大多数服务器端脚本语言的工作方式(包括PHP,JSP和ASP)创建的一种假象。这code只存在于服务器上,它是没有可达形式的客户端(浏览器)没有某种形式的远程调用。

您可以看到这方面的证据,如果你问你的浏览器显示页面的源代码code。在那里,你将不会看到PHP code,这是因为PHP code未发送给客户端,因此它不能从客户端执行。这就是为什么你需要做一个远程调用可以让客户端引发的PHP code的执行。

如果您不使用窗体(如上图所示),你可以从JavaScript的远程调用一个小东西叫做阿贾克斯的。您可能还需要考虑,如果你想用PHP做什么都可以用JavaScript直接完成。


如何调用的另一个的PHP文件?

使用的一种形式做呼叫。你可以把它给用户定向到particlar文件:

 <形式的行动=myphpfile.php>
  <输入类型=提交值=点击我!>
< /形式GT;
 

用户最终会在页面 myphpfile.php 。为了使当前页面的工作,设置动作为空字符串(这是我在我早期给你的例子一样)。

  

我只是想将其链接到一个PHP文件,该文件将在服务器上创建永久的博客文章,这样,当我重新加载页面,后是仍然存在。

您想使服务器上的操作,你应该让你的表格有你需要的字段(即使 TYPE =隐藏和使用 POST ):

 <形式的行动=的方法=POST>
  <输入类型=文字值=默认值,你可以编辑姓名=MyField的与GT;
  <输入类型=提交值=后>
< /形式GT;
 


  

什么我需要了解它来调用一个PHP文件,该文件将创建一个按钮preSS的文本文件?

请参阅: 如何写入到PHP中的文件


如何您收到来自POST数据到服务器?

我很高兴你问...既然你是一个<打击>福利局初学者,我会给你一个小的模板,你可以遵循:

 &LT; PHP
    如果($ _ SERVER ['REQUEST_METHOD'] ===POST)
    {
        // OK,我们得到了一个帖子,可能是从一种形式,从$ _ POST读取。
        后续代码var_dump($ _ POST,); //使用这个,看看有什么信息,我们得到了!
    }
    其他
    {
       //你可以假设你有一个GET
       后续代码var_dump($ _ GET); //使用这个,看看有什么信息,我们得到了!
    }
 ?&GT;
 &LT;!DOCTYPE HTML&GT;
 &LT; HTML LANG =EN&GT;
   &LT; HEAD&GT;
     &LT;元字符集=utf-8&GT;
     &LT;标题&gt;页面标题&LT; /标题&GT;
   &LT; /头&GT;
   &LT;身体GT;
     &LT;形式的行动=的方法=POST&GT;
       &LT;输入类型=文字值=默认值,你可以编辑姓名=MyField的与GT;
       &LT;输入类型=提交值=后&GT;
     &LT; /形式GT;
   &LT; /身体GT;
 &LT; / HTML&GT;
 

注意:的,你可以删除的var_dump ,它只是用于调试目的


如何...

我知道下一个阶段,你会问如何:

  1. 如何传递变量形成一个PHP文件到另一个?
  2. 如何记住用户/做一个登录?
  3. 如何避免是烦人的消息出现,当你重新加载页面?

目前是一个单一的答案:会话

我给了一个更广泛的模板后重定向-GET

 &LT; PHP
    如果($ _ SERVER ['REQUEST_METHOD'] ===POST)
    {
        后续代码var_dump($ _ POST,);
        //做的东西...
        //结果写入会议
        在session_start();
        $ _SESSION ['东西'] = $东西;
        //你可以存储的东西,如用户ID,这样你就可以remeember他。
        //重定向:
        头('位置:',真的,303);
        //重定向会导致浏览器的GET请求
        //操作的结果是在会话变量
        //它具有空位置,因为我们都重定向到同一页
        //否则使用'头('位置:anotherpage.php',真的,303);`
        出口();
    }
    其他
    {
        //你可以假设你有一个GET
        后续代码var_dump($ _ GET); //使用这个,看看有什么信息,我们得到了!
        //从会议材料
        在session_start();
        如果(array_key_exists('东西',$ _SESSION))
        {
           $东西= $ _SESSION ['东西'];
           //我们得到了东西
           //以后使用present的操作的结果给用户。
        }
        //从会议明确的东西:
        取消设置($ _ SESSION ['东西']);
        //设置标题
        标题(内容类型:text / html的;字符集= UTF-8);
        //这个头告诉什么是我们发送的浏览器。
        //它说我们是在UTF-8编码发送HTML
    }
 ?&GT;
&LT;!DOCTYPE HTML&GT;
&LT; HTML LANG =EN&GT;
  &LT; HEAD&GT;
    &LT;元字符集=utf-8&GT;
    &LT;标题&gt;页面标题&LT; /标题&GT;
  &LT; /头&GT;
  &LT;身体GT;
    &LT;?PHP的,如果(使用isset($东西)){回声&LT;跨度&GT;'$的东西'&LT; / SPAN&GT;'}取代;?
    &LT;形式的行动=的方法=POST&GT;
      &LT;输入类型=文字值=默认值,你可以编辑姓名=MyField的与GT;
      &LT;输入类型=提交值=后&GT;
    &LT; /形式GT;
  &LT; /身体GT;
&LT; / HTML&GT;
 

请看看php.net任何函数调用你不承认。另外 - 如果你不已经 - 获得HTML5的一个很好的教程

此外,使用UTF-8 因为UTF-8


备注

  

我做一个简单的博客网站为我自己和我已经得到了code的网站和JavaScript的,可以采取我写的文字区域后,立即显示出来。

如果您使用的是一个CMS(code preSS是,Joomla,Drupal的...等)?使把一些约束上你是怎么做的事情。

另外,如果你使用的是一个框架,你应该看看它们的文档,或要求在他们的论坛/通讯录/讨论页/接触或尝试问作者。


好吧...但我怎么使用Ajax呢?

嗯......阿贾克斯变得容易一些JavaScript库。既然你是一个初学者,我会建议更换 jQuery的

所以,让我们送东西到服务器通过Ajax使用jQuery,我将使用 $。员额代替 $就的这个例子。

 &LT; PHP
    如果($ _ SERVER ['REQUEST_METHOD'] ===POST)
    {
        后续代码var_dump($ _ POST,);
        头('位置:',真的,303);
        出口();
    }
    其他
    {
        后续代码var_dump($ _ GET);
        标题(内容类型:text / html的;字符集= UTF-8);
    }
 ?&GT;
&LT;!DOCTYPE HTML&GT;
&LT; HTML LANG =EN&GT;
  &LT; HEAD&GT;
    &LT;元字符集=utf-8&GT;
    &LT;标题&gt;页面标题&LT; /标题&GT;
    &LT;脚本&GT;
        功能ajaxmagic()
        {
            $。员额(//调用服务器
                test.php的,//在此URL
                {
                    现场:值,
                    名称:约翰福音
                } //而将此数据发送到它
            ).done(//当它完成
                功能(数据)
                {
                    $('#fromAjax')的HTML(数据)。 //与响应更新在这里
                }
            );
        }
    &LT; / SCRIPT&GT;
  &LT; /头&GT;
  &LT;身体GT;
    &LT;输入类型=按钮值=使用AJAX的onclick =ajaxmagic()&GT;
    &所述;跨度的id =fromAjax&GT;&所述; /跨度&GT;
  &LT; /身体GT;
&LT; / HTML&GT;
 

以上code将发送POST请求的页面的test.php

注意的:你可以混合会议 AJAX 之类的东西,如果你想要的。


如何...

  1. <一个href="http://stackoverflow.com/questions/13507230/mysql-connect-on-php/13508200#13508200">How我连接到数据库?
  2. <一个href="http://stackoverflow.com/questions/60174/how-can-i-$p$pvent-sql-injection-in-php/60496#60496">How我做prevent SQL注入?
  3. <一个href="http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php/14110189#14110189">Why我不应该用Mysql_ *功能?

......这些或任何其他的,请再拍问题。这是太多了这一点。

I've looked around for a long while now and I can't find anywhere that answers this seemingly basic question. I don't care if the page reloads or displays the results immediately; I just want to have a button on my website make a PHP file run. That's it. And I've found that all websites either tell you how to run the PHP code in your HTML directly or tell you to use ajax. I'll use ajax if it turns out to be necessary, but there was a time before ajax existed that PHP was used, so I think there's a simpler way. If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?

If it does turn out that ajax is the only way forward, what do I need to know about it to call a PHP file that will create a text file on a button press? I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately. I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

Thanks for taking the time to read and answer.

解决方案


How to make a button call PHP?

I don't care if the page reloads or displays the results immediately;

Good!

Note: If you don't want to refresh the page see "Ok... but how do I Use Ajax anyway?" below.

I just want to have a button on my website make a PHP file run.

That can be done with a form with a single button:

<form action="">
  <input type="submit" value="my button"/>
</form>

That's it.

Pretty much. Also note that there are cases where ajax is really the way to go.

That depends on what you want. In general terms you only need ajax when you want to avoid realoading the page. Still you have said that you don't care about that.


Why I cannot call PHP directly from JavaScript?

If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?

Because the PHP code is not in the HTML just fine. That's an illusion created by the way most server side scripting languages works (including PHP, JSP, and ASP). That code only exists on the server, and it is no reachable form the client (the browser) without a remote call of some sort.

You can see evidence of this if you ask your browser to show the source code of the page. There you will not see the PHP code, that is because the PHP code is not send to the client, therefore it cannot be executed from the client. That's why you need to do a remote call to be able to have the client trigger the execution of PHP code.

If you don't use a form (as shown above) you can do that remote call from JavaScript with a little thing called Ajax. You may also want to consider if what you want to do in PHP can be done directly in JavaScript.


How to call another PHP file?

Use a form to do the call. You can have it to direct the user to a particlar file:

<form action="myphpfile.php">
  <input type="submit" value="click on me!">
</form>

The user will end up in the page myphpfile.php. To make it work for the current page, set action to an empty string (which is what I did in the example I gave you early).

I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

You want to make an operation on the server, you should make your form have the fields you need (even if type="hidden" and use POST):

<form action="" method="POST">
  <input type="text" value="default value, you can edit it" name="myfield">
  <input type="submit" value = "post">
</form>


What do I need to know about it to call a PHP file that will create a text file on a button press?

see: How to write into a file in PHP.


How do you recieve the data from the POST in the server?

I'm glad you ask... Since you are a newb begginer, I'll give you a little template you can follow:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        //Ok we got a POST, probably from a FORM, read from $_POST.
        var_dump($_PSOT); //Use this to see what info we got!
    }
    else
    {
       //You could assume you got a GET
       var_dump($_GET); //Use this to see what info we got!
    }
 ?>
 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta char-set="utf-8">
     <title>Page title</title>
   </head>
   <body>
     <form action="" method="POST">
       <input type="text" value="default value, you can edit it" name="myfield">
       <input type="submit" value = "post">
     </form>
   </body>
 </html>

Note: you can remove var_dump, it is just for debugging purposes.


How do I...

I know the next stage, you will be asking how to:

  1. how to pass variables form a PHP file to another?
  2. how to remember the user / make a login?
  3. how to avoid that anoying message the appears when you reload the page?

There is a single answer for that: Sessions.

I'll give a more extensive template for Post-Redirect-Get

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        //Do stuff...
        //Write results to session
        session_start();
        $_SESSION['stuff'] = $something;
        //You can store stuff such as the user ID, so you can remeember him.
        //redirect:
        header('Location: ', true, 303);
        //The redirection will cause the browser to request with GET
        //The results of the operation are in the session variable
        //It has empty location because we are redirecting to the same page
        //Otherwise use `header('Location: anotherpage.php', true, 303);`
        exit();
    }
    else
    {
        //You could assume you got a GET
        var_dump($_GET); //Use this to see what info we got!
        //Get stuff from session
        session_start();
        if (array_key_exists('stuff', $_SESSION))
        {
           $something = $_SESSION['stuff'];
           //we got stuff
           //later use present the results of the operation to the user.
        }
        //clear stuff from session:
        unset($_SESSION['stuff']);
        //set headers
        header('Content-Type: text/html; charset=utf-8');
        //This header is telling the browser what are we sending.
        //And it says we are sending HTML in UTF-8 encoding
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
  </head>
  <body>
    <?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>;
    <form action="" method="POST">
      <input type="text" value="default value, you can edit it" name="myfield">
      <input type="submit" value = "post">
    </form>
  </body>
</html>

Please look at php.net for any function call you don't recognize. Also - if you don't have already - get a good tutorial on HTML5.

Also, use UTF-8 because UTF-8!


Notes:

I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately.

If are you using a CMS (Codepress, Joomla, Drupal... etc)? That make put some contraints on how you got to do things.

Also, if you are using a framework, you should look at their documentation or ask at their forum/mailing list/discussion page/contact or try to ask the authors.


Ok... but how do I Use Ajax anyway?

Well... Ajax is made easy by some JavaScript libraries. Since you are a begginer, I'll recomend jQuery.

So, let's send something to the server via Ajax with jQuery, I'll use $.post instead of $.ajax for this example.

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        header('Location: ', true, 303);
        exit();
    }
    else
    {
        var_dump($_GET);
        header('Content-Type: text/html; charset=utf-8');
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
    <script>
        function ajaxmagic()
        {
            $.post(                             //call the server
                "test.php",                     //At this url
                {
                    field: "value",
                    name: "John"
                }                               //And send this data to it
            ).done(                             //And when it's done
                function(data)
                {
                    $('#fromAjax').html(data);  //Update here with the response
                }
            );
        }
    </script>
  </head>
  <body>
    <input type="button" value = "use ajax", onclick="ajaxmagic()">
    <span id="fromAjax"></span>
  </body>
</html>

The above code will send a POST request to the page test.php.

Note: You can mix sessions with ajax and stuff if you want.


How do I...

  1. How do I connect to the database?
  2. How do I prevent SQL injection?
  3. Why shouldn't I use Mysql_* functions?

... for these or any other, please make another questions. That's too much for this one.

这篇关于如何调用从HTML或JavaScript的PHP文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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