0

I am creating an API and I want to show a code example in javascript that you can use to invoke the API.

I write a test function in javascript. I would like to be able to execute AND display the code for the javascript function(s) but I would rather only have one copy of the code to make maintenance easier.

Example, I have the following code:

function doauth_test(apikey,username,userpass)
{
    $.ajax({
        url: "/api/v1.2/user.php/doauth/" + username + "/" + userpass + "?apikey=" + apikey,
        type: "GET",
        success: function(data,textStatus,xhr) {
            var obj = JSON.parse(data);
            var authkey = obj.authkey; //store this somewhere for subsequent use
            var user_id = obj.user_id; //store this somewhere for subsequent use
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert("ERROR!  Status code:  " + xhr.status + " Response Text: " + xhr.responseText);
        }
    });
}

I want this code to be something I can EXECUTE and I want it to display the code in a DIV in my documentation example. But I do not want to (ideally) have two copies of this code.

2

2 Answers 2

11

You can call toString() on a function to get its source code.

Alternatively, you can use the DOM to get the text of the <script> tag.

Sign up to request clarification or add additional context in comments.

Comments

2

Just use toString method for your function and it will return your function definition as a string.

alert(doauth_test.toString());

Hope it helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.