javascript 在 onchange 事件中运行 php 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21574282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:13:44  来源:igfitidea点击:

run php query in onchange event

javascriptphpmysql

提问by user3274505

I am newbie here and i having difficulty to construct the mysql query in the javascript. The idea is to run the mysql query when the dropdown value change.

我是这里的新手,我很难在 javascript 中构建 mysql 查询。这个想法是在下拉值更改时运行 mysql 查询。

Below are the code: html code

代码如下:html代码

  <select name="cmbStatus" id="cmbStatus" onchange="check()">
            <option value="All" selected>All</option>
            <option value="New">New</option>
            <option value="In Progress">In Progress</option>
            <option value="Down">Down</option>
            <option value="Complete">Complete</option>
          </select>
            <label>
            <input type="text" name="textfield" id="textfield">
            </label

JS code

JS代码

<script>
function check()
{
    document.getElementById("textfield").value = document.getElementById("cmbStatus").value;
}
</script>

PHP code

PHP代码

$query="SELECT * FROM incident_ticket where Status = 'cmbstatus.value' ";
$result=mysql_query($query);
$num=mysql_numrows($result);

回答by Jite

Php code runs on the server, while javascript (if not server-side javascript) runs on the client.
This means that you can not run php code directly in a javascript function on javascript events, cause its already ran on the server before the page is even loaded on the client.
What is usually used in cases like this, is called AJAX.

Php 代码在服务器上运行,而 javascript(如果不是服务器端 javascript)在客户端上运行。
这意味着您不能直接在 javascript 事件的 javascript 函数中运行 php 代码,因为它甚至在页面加载到客户端之前就已经在服务器上运行了。
在这种情况下通常使用的称为 AJAX。

With ajax you send a request to a php script on the server (with the data that you wish to update), and in the php script you run the query.

使用 ajax,您可以向服务器上的 php 脚本发送请求(使用您希望更新的数据),然后在 php 脚本中运行查询。

There are a few different javascript libraries that makes sending requests like this easy, most people would probably recommend using jQuery, in which a simple ajax post request would look something like:

有几个不同的 javascript 库可以让发送这样的请求变得容易,大多数人可能会推荐使用jQuery,其中一个简单的 ajax 发布请求看起来像这样:

$.ajax({
  type: "POST",
  url: "thephpscript.php",
  data: data,
  success: function(){/*onsuccess*/}
});

But this would require you to load the jquerylibrary before doing the request. Which is another question and for which i would recommend reading the jquery docs: http://www.jquery.com

但这需要您在执行请求之前加载jquery库。这是另一个问题,我建议阅读 jquery 文档:http: //www.jquery.com



Furthermore:
I would really recommend that you do NOT use the mysql_*functions in PHP either.
The mysql_*api is deprecated and will be removed in future versions of php.
The code you got in your example is also open for sql-injections, which is very bad.
Use mysqlior PDOinstead, and either escape the data before using it in query or use prepared statements.

此外:
我真的建议您不要使用mysql_*PHP 中的函数。
mysql_*api 已弃用,将在未来版本的 php 中删除。
您在示例中获得的代码也对sql-injections开放,这非常糟糕。
改用mysqliPDO,并在查询中使用数据之前转义数据或使用准备好的语句

回答by Jori

The only way to do that is using AJAX(or similar, but with other data encapsulation methods, like JSON), which is a very broad topic. Too broad to be explained here in detail, but I will give an overview.

唯一的方法是使用AJAX(或类似的,但使用其他数据封装方法,如JSON),这是一个非常广泛的主题。太宽泛了,无法在这里详细解释,但我会给出一个概述。

Basically AJAX (Asynchronous Javascript And XML) is a way of asynchronously requesting server information by using XML encoding. As the name suggest you will be using Javascript. The Javascript API in most browsers provide in this need with the XMLHttpRequestobject (or ActiveXObjectin older IE's). So lets create a new object:

基本上 AJAX(Asynchronous Javascript And XML)是一种使用 XML 编码异步请求服务器信息的方式。顾名思义,您将使用 Javascript。大多数浏览器中的 Javascript API 提供了XMLHttpRequest对象(或ActiveXObject在较旧的 IE 中)的这种需求。所以让我们创建一个新对象:

ajax = new XMLHttpRequest();

This object provides a few methods and fields, but we will only discuss the most important ones: open(), send(), onreadystatechange, readyState, statusand responseXML. To load a webpage (can be anything, but usually this is xml or generated xml from a php page, in your example we are reading nothing, but just requesting to trigger a PHP script) we use the open()method, like this (just an example):

此对象提供的一些方法和字段,但是我们只讨论最重要的:open()send()onreadystatechangereadyStatestatusresponseXML。要加载网页(可以是任何内容,但通常是 xml 或从 php 页面生成的 xml,在您的示例中我们什么也没读,只是请求触发 PHP 脚本)我们使用open()方法,就像这样(只是一个示例):

ajax.open("GET", "some_php_file.php");

Now we have built a request we can send it:

现在我们已经构建了一个可以发送的请求:

ajax.send();

Done! This will most likely trigger your PHP script, but if we want to do it right, we should check for any errors by registering a (anonymous) status change function (the onreadystatechangefield). This function will be triggered when the status of the request chances (e.x. from LOADINGto DONE)

完毕!这很可能会触发您的 PHP 脚本,但如果我们想正确地执行此操作,我们应该通过注册(匿名)状态更改函数(onreadystatechange字段)来检查是否有任何错误。当请求的状态有机会时会触发此函数(例如 from LOADINGto DONE

ajax.onreadystatechange = function()
{
  if (ajax.readyState != 4 || ajax.status != 200)
  {
    // Do some error handling, like displaying a user visible error message or something
    // The requested information is available as an XML object in the responseXML field
  }
}

readyState = 4means that the file has been requested (state is DONE) and statusis the HTTP response status codefor success (200 OK).

readyState = 4表示该文件已被请求(状态为DONE)并且status是成功的HTTP 响应状态代码( 200 OK)。

You can also use the jQuerylibrary, which simplifies this, but implements essentially the same process.

您还可以使用jQuery库,它简化了这一过程,但实现了本质上相同的过程。

Hope this helps!

希望这可以帮助!

回答by krishna

Use ajax to transfer value to a php file and execute query in that php file on changing the select value

使用 ajax 将值传输到 php 文件并在更改选择值时在该 php 文件中执行查询

$("#cmbStatus").onchange(function(e) {


jQuery.post("runquery.php", {

selcval:$("#cmbStatus").val()

},  function(data, textStatus){



});

});

in runquery.phpexecute the php code what you want to perform on change of select value like this

runquery.php执行 php 代码时,你想像这样更改选择值时执行的操作

$query="SELECT * FROM incident_ticket where Status = '".$_POST['selcval']."' ";
$result=mysql_query($query);
$num=mysql_numrows($result);

回答by Michal Artazov

As already mentioned, problem is that PHP script runs on the server while JS runs "real-time" in the browser. You're goal can be acomplished quiet easily though.

如前所述,问题是 PHP 脚本在服务器上运行,而 JS 在浏览器中“实时”运行。不过,您的目标可以轻松完成。

The idea is that you'll bind the AJAX call to the onchangeevent. I recommend using jQuery for that.

这个想法是您将 AJAX 调用绑定到onchange事件。我建议为此使用 jQuery。

JS

JS

$('#cmbStatus').change(function() {
    $.post("script.php", { value: this.value });
    $('#textfield').val(this.value);
});

script.php

脚本文件

$query="SELECT * FROM incident_ticket where Status = '" . $_POST['value'] . "' ";
$result=mysql_query($query);
$num=mysql_numrows($result);

Replace script.phpwith the valid url of the script. I didn't test it so you'll maybe need to change something but I think you'll get the idea.

替换script.php为脚本的有效 url。我没有测试它,所以你可能需要改变一些东西,但我想你会明白的。

回答by Jignesh Patel

You need to use ajax to execute php code when user change dropdown value on html page.

当用户更改 html 页面上的下拉值时,您需要使用 ajax 来执行 php 代码。

回答by Akhil Sidharth

Use Ajax. you cant directly run MySQL from Javascript. What you can do is, on its on change, using ajax transfer it to a different PHP page, where you can run your SQL script

使用阿贾克斯。你不能直接从 Javascript 运行 MySQL。您可以做的是,在更改时,使用 ajax 将其传输到不同的 PHP 页面,您可以在其中运行 SQL 脚本