简体   繁体   中英

return data in javascript with Python

I am creating a website with Python, Javascript (JQuery) and AJAX. I know to execute a Python script with Ajax, but I don't know to return data to Javascript with Python.

For example, if there is a mistake in a form, I would like send an alert ("The mail is incorrect"). I know that with PHP, I can used echo "something" but I don't know how to take that with Python.

def secure_mail(mail):
    if mail == "":
        error = "the mail is empty"
        print error

Thank you for your help !

In your ajax success message or error function defined in your ajax method you would want to receive back JSON data which will contain your specific error as determined by your Python backend.

so in your python backend create a dictionary.

import json
returnValue = {'error': 'you messed up something'}

## serialize to json string
return json.dumps(returnValue)

Than in your ajax method data.error would equal "you messed up something"

Depending on your web framework of choice (django, flask) the concept of handling the request and returning a dictionary as a json string would be similar.

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