简体   繁体   中英

Call PHP function with jquery $.ajax return json

How can I call (if even possible) a PHP function from javascript targeting one method just like ASP.NET.

PHP:

...
function a($some_string){
return json_encode(array(
                "username" => "bob",
                "items" => array(
                        "item1" => "sandwich",
                        "item2" => "applejuice"
                )
        ));
}

JS:

    $.ajax(
        {url:"index.php/a", 
        type:"POST",
        contentType:"application/json; charset=utf-8",
                    data:{some_string:"blabla"},
        dataType:"json",
        success:function(data){
            alert(data);
            },
        error:function(a,b,c){
            }
        });

In C#:

[WebMethod()]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static object a(string some_string)
{
  return new { 
                user_name = "bob", 
                items = new { 
                    item1 = "sanwitch", 
                    item2 = "applejuice" 
                    }
                };
        }

Thanks,
Péter

You can just put that one function in a PHP file alone. Then run the function within that file (so it echoes out the JSON). Have ajax call that file.

In your case:

echo a($string);

If you were willing to explore an alternative to Jquery, there is a tool called XAJAX that allows you to directly call PHP functions asynchronously via AJAX. It's a pretty nifty tool, though the support and forums are a bit cryptic. For those who are hardcore PHP (but not JAVASCRIPT) guys, this tool is a great option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM